Using the `else` block in loops Flashcards
7 cards from real PCEP practice questions. Tap to flip, then mark Knew It or Still Learning โ missed cards come back until you master them.
Read the first 7 Using the `else` block in loops flashcards as text
Which use case is the `else` clause on a loop MOST commonly used for in Python?
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).
What is printed? for i in range(1, 4): print(i) else: print('end')
Answer: 1 2 3 end
The loop prints 1, 2, 3 normally and then the else block prints 'end' since no break occurred.
Does `continue` prevent the `else` block of a loop from executing?
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.
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')
Answer: found
x==3 triggers break, so else is skipped, found is True, and 'found' is printed.
How many times does the else block execute in a loop that runs to completion?
Answer: Exactly once, after the loop finishes
The else block of a loop executes exactly once after the loop body finishes all iterations naturally.
What is the result of this code? for i in range(3): pass else: pass print('after')
Answer: after
Both the loop body and else block execute pass (no-op), then 'after' is printed.
Which keyword exits a loop and causes its `else` block to be skipped?
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.