Consider the following code se
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 erroron?
0: ans = input(“Yes/No? “)1: if ans == “Yes”:2: print(“Confirmed!”)3: else4: 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 theif-statement block?
A comment # |
||
} |
||
The code is less indented than the previous line |
||
; |
Answer:
ANSWER FIRSTQUESTION:-
count = 1while count<=10: print(count,end=" ")
So the error in the above code is that it is an infiniteloop.
What is an infinite loop?
In simple words, it is a non- terminating loop. So thestatements inside the loop will keep on executing endlessly. In theabove example, it will keep printing 1 on the output window. Thisis because the loop will keep on executing until the value of theloop is less than equal to 10. And here count is 1 and there isnothing inside the loop that is changing its value.
ANSWER SECONDQUESTION:-
0: ans = input("Yes/No? ")1: if ans == "Yes":2: print("Confirmed!")3: else4: print("Not Confirmed!")
In the above code, the error is in the thirdline. There is a syntax error here. unlike otherprogramming languages like C, C++, and Java the if-else statementends 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 = 10while(x>0): print(x-1)
It will print 9,9,9,9,9,9(Forever). Again, itis a case of an infinite loop. and x is 10 and the statement insidewhile i.e
print(x-1) will keep on printing 9 forever because the value ofx will always remain greater than 0 as we don’t have any updatestatement or expression inside the loop to change its value.
In Python, how do you know that you have reached the endof the if-statement block?
ANSWER- Unlike languages like C, C++, and JavaPython works on indentation. So the end of the if-else will bedetermined by its indentation.
E.g:-
x = 5if(x==5): print "Hi, I am five" print "Have a nice day" #end of ifx=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