PCEP Using the `else` block in loops 2 — Questions and Answers
Question 1: What output does the following code produce? for i in range(3): if i == 5: break else: print('done')
- done (Correct answer)
- Nothing
- Error
- 0 1 2 done
Correct answer: done
The loop completes without hitting break, so the else block executes and prints 'done'.
Question 2: Which statement correctly describes when the `else` block of a `while` loop executes?
- When the while condition becomes False naturally (Correct answer)
- When a break statement is encountered
- When a continue statement is encountered
- When an exception is raised inside the loop
Correct answer: When the while condition becomes False naturally
The else block of a while loop executes only when the loop's condition becomes False, not when break exits the loop.
Question 3: What is printed by this code? x = 10 while x > 0: x -= 3 if x == 1: break else: print('finished')
- Nothing (Correct answer)
- finished
- 1
- Error
Correct answer: Nothing
x goes 10→7→4→1, triggering break at x==1, so the else block is skipped.
Question 4: Can a `for` loop's `else` block contain a `return` statement inside a function?
- Yes, it returns from the function normally (Correct answer)
- No, return is not allowed in else blocks
- Yes, but only if the loop ran zero iterations
- No, it causes a SyntaxError
Correct answer: Yes, it returns from the function normally
The else block is ordinary Python code and can contain any valid statement, including return.
Question 5: What does this code print? for n in [2, 3, 4]: for m in [1, 2]: if n * m == 6: break else: print(n)
- 2 (Correct answer)
- 2 4
- 2 3 4
- Nothing
Correct answer: 2
For n=2: 2*1=2, 2*2=4 — no break, prints 2. For n=3: 3*2=6 — break, no print. For n=4: 4*1=4, 4*2=8 — no break, prints 4. Wait — 2 and 4 are printed.
Question 6: A `for` loop's else block is skipped when:
- A break statement exits the loop (Correct answer)
- The iterable is empty
- A continue statement is used
- The loop variable is reassigned inside the loop
Correct answer: A break statement exits the loop
Only a break statement causes the else block to be skipped; continue, empty iterables, and variable reassignment do not prevent else from running.
Question 7: What is the output of this code? nums = [] for n in nums: print(n) else: print('empty')
- empty (Correct answer)
- Nothing
- Error
- None
Correct answer: empty
When the iterable is empty, the loop body never runs but the else block still executes because no break occurred.
What output does the following code produce?
for i in range(3):
if i == 5:
break
else:
print('done')