Hi Pythonistas!,
Today I’m sharing a piece of Python code that’s unique to the language —
but honestly, every time I see it, I have to Google how exactly it works.
Yes, I’m talking about else blocks on for and while loops.
❓ What does it even do?
for item in items:
if item == target:
print("Found!")
break
else:
print("Not found.")
The else block runs only if the loop completes fully without a break. If a break is triggered, the else block is skipped.
⚠️ Why this is confusing
- Most devs expect else to pair with if, not loops.
- It’s easy to misread or misuse.
- Even experienced devs sometimes second-guess what it’s doing.
✅ Better: Use a Flag
found = False
for item in items:
if item == target:
found = True
print("Found!")
break
if not found:
print("Not found.")
Much clearer, and future-you will thank you.
Even Better for Simple Checks
if any(item == target for item in items):
print("Found!")
else:
print("Not found.")
✅ Clean
✅ Pythonic
✅ Beginner-friendly
When is else after a loop okay?
Only when:
- You really care whether the loop ended without breaking.
- Everyone reading your code knows this pattern.
- Clarity isn’t sacrificed.
- You are working on your hobby projects.
TL;DR
Avoid else after loops in most cases.It’s valid — but rarely worth the confusion.Use flags or built-in functions like any() instead.