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

Part 03 / Topic 2 of 12

Nested if

You can put an if inside another if. Use it when the second check only makes sense after the first passes. Keep nesting shallow (2 levels max). Often and makes it flatter.

Real-world example: a movie ticket counter checks age first, then checks the ticket.

age = 20
has_ticket = True

if age >= 18:
    if has_ticket:
        print("Enjoy the movie!")
    else:
        print("Please buy a ticket.")
else:
    print("Sorry, this movie is 18+.")
# Enjoy the movie!

# Same idea, flatter with `and`
if age >= 18 and has_ticket:
    print("Entry allowed")  # Entry allowed

๐Ÿ” Going deeper: and / or short-circuit: Python stops as soon as the answer is known. In age >= 18 and has_ticket, if the age check is False, has_ticket is never looked at.

Done here? The practice set for Part 3 โ€” 7 exercises with solutions โ€” is on the part page.

Search the guide