for...else 👉 Did you know
else isn't just for if statements? Python has a unique feature almost never mentioned in beginner tutorials: you can attach an
else block directly to a for or while loop.🔹 How It Works
The
else block executes ONLY if the loop finishes completely without hitting a break statement.🔹 The Difference
❌ Traditional Way (Requires a messy flag variable):
found = False
for user in users:
if user == "Alex":
found = True
break
if not found:
print("User not found!")
✅ Pythonic Way (Using
for...else):for user in users:
if user == "Alex":
print("User found!")
break
else:
print("User not found!")
🔹 Why Use It?
✔️ Eliminates unnecessary boolean flags (like
found = True).✔️ Cleaner, more readable syntax for search functions.