For Loops with else Clauses
The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block ), else we process another block of statements (called the else-block ). The else clause is optional.
The Completion Path
A Python while loop can have an else clause. This else clause is not attached to an if statement inside the loop. It belongs to the loop itself and runs only when the loop finishes naturally, meaning its condition becomes false. If the loop stops because of break, the else block is skipped.
Tracing a Search
What do you think happens?
What happens when this search reaches the end of the list without finding the target?
Reveal answer
The else block runs.
The search condition eventually becomes false because the index is no longer less than the length of the list. The loop therefore ends naturally rather than through break.
numbers = [2, 4, 6, 8, 10]
target = 7
index = 0
while index < len(numbers):
if numbers[index] == target:
print("found")
break
index += 1
else:
print("not found")- 1The search begins with index equal to 0.
- 2Each iteration compares the current list element with target.
- 3When the comparison is false, index increases by 1.
- 4After all five elements have been checked, the loop condition becomes false.
- 5The else block runs and reports that the target was not found.
- The loop checks each element while index is less than the list length.
- The target is not found, so break is never executed.
- After the final element is checked, index reaches 5 and the condition index <
len(numbers)becomes false. - Because the loop ends naturally, the else block prints the not found message.
not foundThe Two Exit Conditions
| How the loop ends | What happens to else |
|---|---|
| The loop condition becomes false | The else block executes |
| The loop reaches break | The else block is skipped entirely |
The loop else clause responds to how the loop terminates.
The most useful way to read while-else is: continue the loop while work remains; run else if the work completes without interruption. In a search, the else block can report that no match was found. In validation, it can report that validation completed successfully. In other processing patterns, it can hold completion or post-loop logic. The defining rule remains the same: break indicates early termination, while a false loop condition indicates natural completion.
Loop Else and If Else
An if-else pair chooses between two blocks based on whether one condition is true or false. A loop else clause is different: it reports that the loop completed naturally. The trigger is not simply a false test inside the loop. The loop must finish because its controlling condition becomes false, rather than being interrupted by break.
Avoiding a Search Flag
found = False
index = 0
while index < len(numbers):
if numbers[index] == target:
found = True
break
index += 1
if not found:
print("not found")A separate flag records whether the search found a match.
index = 0
while index < len(numbers):
if numbers[index] == target:
break
index += 1
else:
print("not found")The loop else clause handles natural completion, so a flag variable is not needed.
The while-else pattern can express the distinction between a successful early search and an unsuccessful complete search directly. Use break when the desired item or condition is found. Put the completion message or validation result in else. If no break occurs, the loop eventually ends naturally and the else block runs. This eliminates the need for a separate flag variable in these search and validation patterns.
processing completedMistakes with Loop Else
Common mistake Assuming else runs whenever the loop body finishes its last iteration.
What it looks likeA search finds its target and executes break on the final iteration.
Why it failsThe loop ended through break, so the else clause is skipped even though the target was found near the end.
Do this insteadTrack the exit mechanism: natural termination runs else; break does not.
Common mistake Treating loop else as an if-else attached to a condition inside the loop.
What it looks likeReading while condition: as if condition: and expecting else to describe one failed comparison.
Why it failsThe loop else belongs to the loop and describes how the entire loop terminated.
Do this insteadInterpret else only after considering the loop's complete control flow.
Common mistake Adding a flag variable automatically for every search.
What it looks likeSetting found = False, changing it when a match appears, and checking it after the loop.
Why it failsFor the search and validation pattern described here, while-else already distinguishes early termination from natural completion.
Do this insteadUse break for the early-success path and else for the no-break completion path when that structure is clear.
If the loop condition is already false before the first iteration, the loop has completed naturally, so its else block executes. The key rule is still termination by a false condition rather than termination by break.
Control-Flow Practice
Write a while-else search for target = 6 in the list [2, 4, 6, 8]. Print found when the target is encountered and use break. In the else block, print not found. Before running it, decide whether the else block should execute.
Hints
- Start an index at 0 and continue while the index is less than the list length.
- Increase the index when the current element is not the target.
- A match should exit the loop with break.
Predicting the Search Result
A search checks [2, 4, 6, 8] for target 6. Does the loop else block run?
- 1Begin
The loop starts at the first list element and checks each value.
- 2Find the target
When the loop reaches 6, the search condition succeeds.
- 3Exit early
The search uses break after finding the target, so the loop does not continue to natural completion.
- 4Apply the rule
Because break ended the loop, the else block is skipped.
The found message runs, and the not found message in else does not run.
Key Takeaways
- 1Python while loops can include an else clause, unlike the loop behavior described for C and C++.
- 2The else block executes when the loop condition becomes false and the loop ends naturally.
- 3A break statement skips the loop else block entirely.
- 4While-else is useful for search, validation, completion, and post-loop logic.
- 5This pattern can remove the need for a separate flag variable when the control flow clearly distinguishes early termination from natural completion.
At a glance
- A loop else clause belongs to the loop, not to an if statement inside it.
- Natural termination through a false loop condition runs else.
- Early termination through break skips else.
- The pattern is especially useful for reporting unsuccessful searches or completed validation without a flag variable.