PCEP Using the `else` block in loops 3 — Questions and Answers
Question 1: Which use case is the `else` clause on a loop MOST commonly used for in Python?
- Detecting that a search completed without finding a target (Correct answer)
- Handling exceptions raised in the loop body
- Executing cleanup code after any loop exit
- Printing the final loop variable
Correct answer: Detecting that a search completed without finding a target
The loop else pattern is idiomatically used to run code only when a target was not found (i.e., break was never triggered).
Question 2: What is printed? for i in range(1, 4): print(i) else: print('end')
- 1 2 3 end (Correct answer)
- 1 2 3
- end
- 1 2 3 end end
Correct answer: 1 2 3 end
The loop prints 1, 2, 3 normally and then the else block prints 'end' since no break occurred.
Question 3: Does `continue` prevent the `else` block of a loop from executing?
- No, continue does not affect the else block (Correct answer)
- Yes, continue skips the else block
- Only if continue appears in the last iteration
- Only inside a while loop
Correct answer: No, continue does not affect the else block
continue only skips the current iteration's remaining body; it does not exit the loop, so the else block still executes normally.
Question 4: What output does this produce? found = False for x in range(5): if x == 3: found = True break else: print('not found') if found: print('found')
- found (Correct answer)
- not found found
- not found
- found not found
Correct answer: found
x==3 triggers break, so else is skipped, found is True, and 'found' is printed.
Question 5: How many times does the else block execute in a loop that runs to completion?
- Exactly once, after the loop finishes (Correct answer)
- Once per iteration
- Zero times
- It depends on the iterable length
Correct answer: Exactly once, after the loop finishes
The else block of a loop executes exactly once after the loop body finishes all iterations naturally.
Question 6: What is the result of this code? for i in range(3): pass else: pass print('after')
- after (Correct answer)
- Nothing
- Error
- pass
Correct answer: after
Both the loop body and else block execute pass (no-op), then 'after' is printed.
Question 7: Which keyword exits a loop and causes its `else` block to be skipped?
- break (Correct answer)
- continue
- pass
- return
Correct answer: break
break is the only loop control keyword that causes the else block to be skipped; return exits the whole function but also skips the else block.
Which use case is the `else` clause on a loop MOST commonly used for in Python?