Python Loop else Examples
Short, runnable programs that show python else on loops in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python else on Loops lesson.
1Is this coupon code valid?
The textbook search pattern. A match prints the success message and breaks; if the loop ends with no match, the else explains why nothing was applied.
valid_codes = ["SAVE10", "FREESHIP", "WELCOME"]
code = "BIRTHDAY"
for valid in valid_codes:
if code == valid:
print("Coupon applied:", code)
break
else:
print("Sorry,", code, "is not a valid coupon")Expected outputSorry, BIRTHDAY is not a valid coupon
2Validation: break on the first problem
Here the break means "something is wrong", so the else means "everything checked out". This is not a search at all, but it uses the same rule.
scores = [72, 88, 105, 64]
for score in scores:
if score < 0 or score > 100:
print("Invalid score:", score)
break
else:
print("All scores are valid")Expected outputInvalid score: 105
3A while loop with else
The else runs when the condition temperature > 40 becomes False. If the safety break fired first, the else would be skipped.
temperature = 90
minutes = 0
while temperature > 40:
temperature -= 15
minutes += 1
if minutes == 10:
print("Taking too long, check the fridge")
break
else:
print("Cooled down after", minutes, "minutes")Expected outputCooled down after 4 minutes
4An empty list still runs the else
No items means zero rounds and no break, so the else runs anyway. If an empty list needs special treatment, test for it before the loop.
cart = []
for item in cart:
print("Packing", item)
else:
print("Finished packing", len(cart), "items")Expected outputFinished packing 0 items
5The same search with a position and no else
When you need to know where the match was, store the position in a variable that starts as None. After the loop, one if handles both outcomes.
usernames = ["asha", "ben", "chen"]
wanted = "ben"
found_at = None
for position, name in enumerate(usernames):
if name == wanted:
found_at = position
break
if found_at is None:
print(wanted, "is available")
else:
print(wanted, "is taken, found at position", found_at)Expected outputben is taken, found at position 1
Practise next
Python else on Loops exercises → Back to the lesson
Python for Loops examplesPython while Loops examplesPython break and continue examples