Python Loop else Clause
Updated 7 min read Aimerscrew
Most languages only let you attach else to an if. Python also lets you attach it to loops. The Python for else (and while else) clause runs a block of code only if the loop finished without hitting break. It sounds odd at first, but once you see the search pattern it solves, it becomes a neat tool.
🌍 Real-life example
A security guard checks a guest list for your name. If they find it, they stop reading and wave you in (that's break). If they reach the end of the list without finding you, then they say "Sorry, you're not on the list." That last part, which only happens when the search went all the way through, is the loop's else.
What is the else clause on a loop?
A loop else is a block written right after a for or while loop, at the same indentation as the loop keyword. Python runs it when the loop ends normally:
- a
forloop ends normally when it runs out of items; - a
whileloop ends normally when its condition becomesFalse.
If the loop is ended by break, which you learned in break, continue and pass, the else block is skipped.
for song in ["Intro", "Sunrise", "Outro"]:
print(f"Playing {song}")
else:
print("Playlist finished.")
Playing Intro
Playing Sunrise
Playing Outro
Playlist finished.
No break happened, so the else block ran after the last song.
What happens when the loop breaks?
Add a break and the picture changes. Here, playback stops if a song is marked as explicit:
for song in ["Intro", "Explicit Mix", "Outro"]:
if song == "Explicit Mix":
print("Parental controls: playback stopped.")
break
print(f"Playing {song}")
else:
print("Playlist finished.")
Playing Intro
Parental controls: playback stopped.
"Playlist finished." never appears, because the loop ended with break.
💡 Tip
Many Python developers mentally read a loop's else as nobreak. "for each item... nobreak: do this" makes the meaning instantly clear.
The for-else search pattern
The classic use of for...else is searching. You break as soon as you find a match, and the else handles the "not found" case. Here's a sign-up form checking whether a username is already taken:
taken_usernames = ["sky_runner", "pixel_cat", "jazzfan99", "neo_coder"]
new_username = "pixel_cat"
for name in taken_usernames:
if name == new_username:
print(f"Sorry, {new_username} is already taken.")
break
else:
print(f"{new_username} is available!")
Sorry, pixel_cat is already taken.
Change new_username to a name that isn't in the list, and the loop checks every item, never breaks, and runs the else:
taken_usernames = ["sky_runner", "pixel_cat", "jazzfan99", "neo_coder"]
new_username = "moon_baker"
for name in taken_usernames:
if name == new_username:
print(f"Sorry, {new_username} is already taken.")
break
else:
print(f"{new_username} is available!")
moon_baker is available!
📝 Note
For a plain "is it in the list?" check, if new_username in taken_usernames: is shorter. The for-else pattern earns its place when the test is more than simple equality, such as ignoring upper and lower case or checking several conditions per item.
Real-world example: is a number prime?
A prime number can only be divided evenly by 1 and itself. To test a number, try every possible divisor. If one divides evenly, it's not prime, so break. If none do, the else declares it prime.
number = 29
for divisor in range(2, number):
if number % divisor == 0:
print(f"{number} is not prime (divisible by {divisor}).")
break
else:
print(f"{number} is prime!")
29 is prime!
Put that check inside another loop and you can list every prime up to 20. The else belongs to the inner for, so it runs once for each number that had no divisor:
for number in range(2, 21):
for divisor in range(2, number):
if number % divisor == 0:
break
else:
print(number, end=" ")
2 3 5 7 11 13 17 19
For 2, range(2, 2) is empty, so the inner loop runs zero times and the else runs straight away. That's correct, since 2 is prime.
How does while-else work?
A while loop's else runs when the condition turns False, and is skipped if the loop ends with break:
seconds = 3
while seconds > 0:
print(seconds)
seconds -= 1
else:
print("Liftoff!")
3
2
1
Liftoff!
A more useful example is a login with limited attempts. Success breaks out of the loop; running out of attempts lets the loop end normally, which triggers the else:
attempts = 0
while attempts < 3:
pin = input("Enter your PIN: ")
if pin == "4071":
print("Card unlocked.")
break
attempts += 1
print("Wrong PIN.")
else:
print("Card blocked. Please contact your bank.")
In this run the user typed 1234, 0000 and 9999, all wrong:
Enter your PIN: 1234
Wrong PIN.
Enter your PIN: 0000
Wrong PIN.
Enter your PIN: 9999
Wrong PIN.
Card blocked. Please contact your bank.
Had they typed 4071 at any point, the program would print Card unlocked. and skip the else.
Loop else vs a flag variable: when should you use it?
Without else, you'd track the result with a flag variable, a boolean that records whether something happened:
taken_usernames = ["sky_runner", "pixel_cat", "jazzfan99"]
new_username = "moon_baker"
found = False
for name in taken_usernames:
if name == new_username:
found = True
break
if not found:
print(f"{new_username} is available!")
moon_baker is available!
Both versions are correct. Here's how to choose:
Loop else | Flag variable | |
|---|---|---|
| Extra variable needed | No | Yes |
| Readable for beginners | Only once you know the rule | Very clear |
| Result usable later in the program | No, it only runs a block | Yes, found stays available |
| Best for | Short searches with a "not found" message | When you need the answer in several places |
A good rule: use loop else when the "not found" action sits right after the loop and nothing else needs to know. If you're working with a team that rarely sees it, a short comment like # no break next to the else helps.
Common mistakes with loop else
1. Indenting else under the if instead of the loop
for name in ["sky_runner", "pixel_cat"]:
if name == "pixel_cat":
print("Taken!")
break
else:
print("Available!")
Available!
Taken!
This else belongs to the if, so it runs for every name that doesn't match. A loop else must line up with the for keyword.
2. Forgetting the break
Without a break inside the loop, a loop's else always runs, which makes it pointless. If your else runs when you didn't expect it, check that the break is actually reached.
3. Thinking else means "the loop didn't run"
for item in []:
print(item)
else:
print("else still runs")
else still runs
An empty loop ends normally with no break, so the else runs. Loop else is about break, not about whether the body ran.
Practice exercise
🏋️ Try it yourself
A café needs to warn customers with nut allergies. Given ingredients = ["flour", "butter", "sugar", "almonds", "eggs"], use a for-else loop that prints Warning: contains almonds! and stops as soon as it finds any nut ("almonds", "peanuts" or "walnuts"). If there are no nuts, print Nut-free recipe.
Show solution
ingredients = ["flour", "butter", "sugar", "almonds", "eggs"]
nuts = ["almonds", "peanuts", "walnuts"]
for ingredient in ingredients:
if ingredient in nuts:
print(f"Warning: contains {ingredient}!")
break
else:
print("Nut-free recipe.")
Warning: contains almonds!
Remove "almonds" from the list and run it again: the loop finishes without breaking and prints Nut-free recipe.
What's next?
Congratulations, you've finished the Control Flow chapter! You've been looping over collections of items for a while now, so it's time to learn them properly. Start Chapter 6 with Python lists.
Key takeaways
- A for or while loop can have an else block, written at the same indentation as the loop keyword.
- The loop else runs only when the loop ends normally, without break.
- If break runs, the else block is skipped; read loop else as "no break".
- The classic use is a search: break when you find a match and put the not-found code in else.
- An empty loop still runs its else block, because no break happened.
- A flag variable does the same job and is better when the result is needed later in the program.
Frequently asked questions
When does the else block of a for loop run in Python?
It runs after the loop has gone through every item without hitting a break statement. If break ends the loop early, the else block is skipped.
Does Python have while else?
Yes. A while loop can have an else block that runs when the condition becomes False. Like for-else, it is skipped if the loop ends with break.
What is for else used for in Python?
It is mostly used for searches. You break out of the loop when you find what you are looking for and put the code for the not-found case in the else block, so you do not need a separate flag variable.
Does the loop else run if the loop never executes?
Yes. If a for loop has nothing to loop over, or a while condition is False from the start, the loop ends without break, so the else block runs.
Is using else with loops good practice?
It is a valid, Pythonic feature that is great for short search loops. Because some developers find it surprising, keep the loop small, or add a short comment such as no break to make the intent clear.