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 does the following function return? def has_even(lst): for n in lst: if n % 2 == 0: break else: return False return True print(has_even([1, 3, 5]))
Answer: False
No even number found, so break is never hit, the else runs and returns False.
What is the output? i = 0 while i < 3: i += 1 else: print(i)
Answer: 3
The while loop increments i until i==3 (condition becomes False), then else prints i which is 3.
Is it valid Python syntax to have an `else` block on both an inner and outer `for` loop?
Answer: Yes, each loop can have its own else block
Each for or while loop can independently have its own else block; nesting does not restrict this.
What is printed by this code? for a in range(2): for b in range(2): if a == b: break else: print(b)
Answer: Nothing
For a=0: b=0, 0==0 triggers break so inner else is skipped. For a=1: b=0 (0!=1), b=1 (1==1) triggers break so inner else is skipped. Nothing is printed.
Which of these correctly implements 'print a message only if a target was NOT found in a list'?
Answer: for x in lst: if x == target: break else: print('not found')
The for/else pattern with break is the idiomatic Python way to print a message only when the target is never found.
What happens when a `while` loop's condition is initially False and it has an `else` block?
Answer: The else block executes immediately
If the while condition is False from the start, the body never runs but the else block still executes because no break occurred.
What is the output of this code? for i in range(5): if i == 2: continue if i == 4: break else: print('no break') print('done')
Answer: done
When i==4, break exits the loop, so the else block is skipped and only 'done' is printed.