The else clause of a for loop — Aptitude Question
The else clause of a for loop: What does this Python program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 105 seconds
Question
What does this Python program print?
for i in range(3, 8):
if i % 4 == 0:
break
else:
print("none")
print(i)Options
- 3
- 4
- 7
- none followed by 7
Show the answer and the worked solution
Correct answer: B. 4
Worked solution
- i takes the value 3 first, and 3 % 4 is 3, so the loop continues.
- i then takes the value 4, and 4 % 4 is 0, so break fires.
- Because the loop was broken out of, the else clause is skipped and none is never printed.
- The loop variable survives the loop and still holds 4, so the program prints 4.
Answer: 4.
The idea
A loop else means 'no break happened', which reads better as a nobreak clause. The loop variable is not scoped to the loop in Python, so it remains available afterwards.
Shortcut. The first multiple of 4 in 3 to 7 is 4, so the loop breaks there; a break skips the else, and i keeps the value 4.
Common trap. 7 assumes the loop variable ends on the last value of range(3, 8), as after a full run; the break at i = 4 stops it there.
All Programming Fundamentals questions · placement mock tests