What is the purpose of a `while` loop in Python?
A
To run a block of code a fixed number of times B
To run a block of code while a condition is True C
To iterate through a list D
To define a function
Analysis & Theory
A `while` loop runs as long as its condition remains True.
How many times will this loop execute?
x = 0
while x < 3:
x += 1
print(x)
A
2 times B
3 times C
4 times D
Infinite loop
Analysis & Theory
It prints 1, 2, 3 — runs three times until `x` becomes 3.
What is required to avoid an infinite `while` loop?
A
A break statement B
A function C
A changing condition inside the loop D
return statement
Analysis & Theory
The loop variable must be updated so that the condition eventually becomes False.
Which keyword can be used to exit a loop early?
A
stop B
exit C
break D
return
Analysis & Theory
`break` exits the loop immediately, even if the condition is still True.
What does this loop do?
x = 1
while x <= 3:
print(x)
x += 1
A
Prints 1 only B
Prints 1, 2, 3 C
Infinite loop D
Syntax error
Analysis & Theory
It prints the values 1, 2, and 3, then stops when x becomes 4.
What is the output of this code?
x = 0
while x < 5:
x += 1
if x == 3:
continue
print(x)
A
1 2 3 4 5 B
1 2 4 5 C
1 2 3 4 D
1 2 3
Analysis & Theory
`continue` skips the print when x == 3, so 3 is not printed.
Which keyword can be used to skip the current iteration of a `while` loop?
A
pass B
skip C
next D
continue
Analysis & Theory
`continue` skips the rest of the loop body and moves to the next iteration.
What happens if the `while` condition is always True?
A
Loop runs once B
Code after the loop runs C
Loop never ends unless `break` is used D
Error
Analysis & Theory
If the condition never becomes False, the loop continues forever unless interrupted with `break`.
What will be printed?
x = 1
while x <= 3:
print(x)
x += 1
else:
print('Done')
A
1 2 3 B
1 2 3 Done C
Done D
1 2 Done
Analysis & Theory
The `else` block runs after the loop condition becomes False.
What is the output?
x = 0
while x < 3:
print(x)
x = x + 1
A
0 1 2 B
1 2 3 C
0 1 2 3 D
0 2 4
Analysis & Theory
The loop prints 0, 1, and 2, then exits when x = 3.