Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

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 else surprising, so add a short comment like # no break: not found when 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.

Search the guide