Part 03 / Topic 9 of 12
Loop else
A for or while loop can have an else block. It runs only if the loop finished without break.
It is perfect for "search, and say if not found". Think of it as "no break happened".
Real-world example: check if a coupon code is valid.
valid_coupons = ["DIWALI50", "NEWUSER", "FREESHIP"]
code = "HOLI20"
for coupon in valid_coupons:
if coupon == code:
print("Coupon applied!")
break
else:
print(f"{code} is not a valid coupon.")
# HOLI20 is not a valid coupon.
๐ Going deeper: many developers find loop
elsesurprising, so add a short comment like# no break: not foundwhen you use it. For a simple "is it there?" check,if code in valid_coupons:is shorter.
Done here? The practice set for Part 3 โ 7 exercises with solutions โ is on the part page.