Member-only story
Python’s Hidden Trick: The else
Clause in Loops! 🤯
Jan 31, 2025
Most developers use else
with if
, but did you know loops in Python can also have an else
clause? 😲
🔹 How It Works
In Python, the else
block in a loop runs only if the loop completes without a break
!
🔹 Example
numbers = [1, 3, 5, 7]
for num in numbers:
if num % 2 == 0:
print(f"Found an even number: {num}")
break
else:
print("No even numbers found!")
📌 Output:
No even numbers found!
💡 Why? The loop didn’t break, so the else
block ran.
🔹 When to Use It?
✅ Searching for an item (but handling cases where it’s not found)
✅ Verifying conditions inside loops
This is a Pythonic trick many developers overlook! Have you ever used else
with loops before? 🤔