Python’s while
loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. Here we present 12 multiple-choice questions to test your knowledge of Python While Loop. Each MCQ has the correct answer with an explanation.
1. What is the basic structure of a while loop in Python?
Answer:
Explanation:
In Python, a while loop is written as 'while' followed by a condition, a colon, and then the statement(s) to execute.
2. How do you ensure a while loop runs at least once regardless of the condition?
Answer:
Explanation:
Python doesn't have a do-while loop construct that guarantees at least one execution of the loop body.
3. What does the 'break' statement do in a while loop?
Answer:
Explanation:
The 'break' statement is used to exit a while loop immediately, regardless of the condition.
4. What is the purpose of the 'continue' statement in a while loop?
Answer:
Explanation:
The 'continue' statement skips the remaining code in the current iteration and proceeds to the next iteration of the loop.
5. How can you use an else statement with a while loop?
Answer:
Explanation:
In Python, the else block after a while loop is executed when the loop condition becomes False.
6. What is the output of the following code?
x = 5
while x > 3:
print(x)
x -= 1
Answer:
Explanation:
The loop decrements x and prints its value as long as x is greater than 3.
7. How do you create an infinite loop?
Answer:
Explanation:
An infinite loop can be created by using 'while True:' or any condition that always evaluates to True.
8. What is the role of the 'else' clause in a while loop?
Answer:
Explanation:
The else clause in a while loop is executed when the loop terminates naturally, without hitting a break statement.
9. What happens if 'continue' is executed in a while loop?
Answer:
Explanation:
The 'continue' statement causes the loop to immediately start the next iteration.
10. What does the following code do?
x = 0
while x < 5:
x += 1
if x == 3:
break
else:
print("Loop completed")
Answer:
Explanation:
The loop is terminated by the break statement when x equals 3, so the else block is not executed.
11. How can a while loop be terminated prematurely?
Answer:
Explanation:
The 'break' statement is used to exit a while loop before the condition becomes False.
12. What is the output of the following code?
count = 0
while count < 5:
count += 1
if count == 3:
continue
print(count)
Answer:
Explanation:
The 'continue' statement skips the print statement when count is 3, so 3 is not printed.