In: Computer Science
Consider the following code segment:
count = 1
while count <= 10:
print(count, end="
")
Which of the following describes the error in this code?
The loop control variable is not properly initialized. |
||
The comparison points the wrong way. |
||
The loop is infinite. |
||
The loop is off by 1. |
Does this code contain an error? If so, what line is the error on?
0: ans = input("Yes/No? ")
1: if ans == "Yes":
2: print("Confirmed!")
3: else
4: print("Not Confirmed!")
line 2 |
||
line 3 |
||
line 1 |
||
No error, this code is fine. |
What is the output of the following code:
x = 10 while(x>0): print(x-1)
9,9,9,...(forever) |
||
9,8,7,6,5,4,3,2,1 |
||
10,9,8,7,6,5,4,3,2,1,0 |
||
9,8,7,6,5,4,3,2,1,0 |
In Python, how do you know that you have reached the end of the if-statement block?
A comment # |
||
} |
||
The code is less indented than the previous line |
||
; |
ANSWER FIRST QUESTION:-
count = 1
while count<=10:
print(count,end=" ")
So the error in the above code is that it is an infinite loop.
What is an infinite loop?
In simple words, it is a non- terminating loop. So the statements inside the loop will keep on executing endlessly. In the above example, it will keep printing 1 on the output window. This is because the loop will keep on executing until the value of the loop is less than equal to 10. And here count is 1 and there is nothing inside the loop that is changing its value.
ANSWER SECOND QUESTION:-
0: ans = input("Yes/No? ")
1: if ans == "Yes":
2: print("Confirmed!")
3: else
4: print("Not Confirmed!")
In the above code, the error is in the third line. There is a syntax error here. unlike other programming languages like C, C++, and Java the if-else statement ends with a :(colon) in python.
So the correct code will look like this:-
ans=input("Yes/No?")
if ans=="Yes":
print ("Confirmed")
else: #This is the error that was fixed
print ("Not confirmed")
ANSWER TO THE THIRD QUESTION:-
x = 10
while(x>0):
print(x-1)
It will print 9,9,9,9,9,9(Forever). Again, it is a case of an infinite loop. and x is 10 and the statement inside while i.e
print(x-1) will keep on printing 9 forever because the value of x will always remain greater than 0 as we don't have any update statement or expression inside the loop to change its value.
In Python, how do you know that you have reached the end of the if-statement block?
ANSWER- Unlike languages like C, C++, and Java Python works on indentation. So the end of the if-else will be determined by its indentation.
E.g:-
x = 5
if(x==5):
print "Hi, I am five"
print "Have a nice day" #end of if
x=x+1
So, here the indentation of the if is
print "Hi, I am five"
print "Have a nice day"
That means it will end after these lines.
The line x=x+1 is not a part of if block.
HAPPY LEARNING