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
What output does the following code produce? for i in range(3): if i == 5: break else: print('done')
Answer: done
The loop completes without hitting break, so the else block executes and prints 'done'.
Which statement correctly describes when the `else` block of a `while` loop executes?
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.
What is printed by this code? x = 10 while x > 0: x -= 3 if x == 1: break else: print('finished')
Answer: Nothing
x goes 10→7→4→1, triggering break at x==1, so the else block is skipped.
Can a `for` loop's `else` block contain a `return` statement inside a function?
Answer: Yes, it returns from the function normally
The else block is ordinary Python code and can contain any valid statement, including return.
What does this code print? for n in [2, 3, 4]: for m in [1, 2]: if n * m == 6: break else: print(n)
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.
A `for` loop's else block is skipped when:
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.
What is the output of this code? nums = [] for n in nums: print(n) else: print('empty')
Answer: empty
When the iterable is empty, the loop body never runs but the else block still executes because no break occurred.