MCQ On Python Loop
MCQ On Python Loop
i = 1
while True:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 2
c) 1 2 3 4 5 6 …
d) 1 3 5 7 9 11 …
Answer: d
Explanation: The loop does not terminate since i is never an even number.
i = 2
while True:
if i%3 == 0:
break
print(i)
i += 2
a) 2 4 6 8 10 …
b) 2 4
c) 2 3
d) error
Answer: b
Explanation: The numbers 2 and 4 are printed. The next value of i is 6 which is
divisible by 3 and hence control exits the loop.
i = 1
while False:
if i%2 == 0:
break
print(i)
i += 2
a) 1
b) 1 3 5 7 …
c) 1 2 3 4 …
d) none of the mentioned
Answer: d
Explanation: Control does not enter the loop because of False.
4. What will be the output of the following Python code?
True = False
while True:
print(True)
break
a) True
b) False
c) None
d) none of the mentioned
Answer: d
Explanation: SyntaxError, True is a keyword and it’s value cannot be changed.
i = 0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
a) 0 1 2 0
b) 0 1 2
c) error
d) none of the mentioned
Answer: b
Explanation: The else part is not executed if control breaks out of the loop.
i = 0
while i < 3:
print(i)
i += 1
else:
print(0)
a) 0 1 2 3 0
b) 0 1 2 0
c) 0 1 2
d) error
Answer: b
Explanation: The else part is executed when the condition in the while statement is
false.
7. What will be the output of the following Python code?
x = "abcdef"
i = "a"
while i in x:
print(i, end = " ")
a) no output
b) i i i i i i …
c) a a a a a a …
d) a b c d e f
Answer: c
Explanation: As the value of i or x isn’t changing, the condition will always evaluate
to True.