Python's else on Loops: The Feature You're Not Using
Source: Dev.to
The Rule
The else block runs only if the loop completes without encountering a break.
while condition:
if found_target:
break
# keep searching
else:
# This runs only if we never broke out
print("Search completed without finding target")
Why This Matters
Consider a search loop. Without else, you need a flag variable:
found = False
index = 0
while index # (incomplete condition)
Note: This is a simplification. Production retry logic typically includes exponential backoff and jitter to avoid overwhelming the server with simultaneous retries from multiple clients.
Why It’s Underused
The naming is confusing. else after a loop doesn’t sound like “run if no break.” It sounds like it should be connected to a conditional.
Some Python developers have argued it should have been called nobreak or finally (though finally already means something different in Python’s exception handling).
The syntax won’t change, so the best approach is to internalize the mental model: else means nobreak.
When To Use It
- Search loops – handle “not found” without a flag
- Retry patterns – handle “all attempts exhausted”
- Validation loops – handle “no valid option found”
Important: It’s only useful for loops that use
breakfor early exit. If your loop doesn’t have abreak, theelsewill always run—which is rarely what you want.
Bonus: Common Infinite Loop Bugs
Bug 1: Forgetting to update the variable
count = 0
while count 0: # <-- missing comparison operator
print(count)
count += 1 # Should be: count -= 1
Bug 2: (Missing in original)
No content provided.
Bug 3: Off‑by‑one with not‑equals
x = 3
while x != 10:
x += 2 # x goes 3, 5, 7, 9, 11... never equals 10
Fix:
x = 1000
print("WARNING: Loop hit safety limit!")
From my upcoming book “Zero to AI Engineer: Python Foundations.”