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/orshort-circuit: Python stops as soon as the answer is known. Inage >= 18 and has_ticket, if the age check isFalse,has_ticketis never looked at.
Done here? The practice set for Part 3 โ 7 exercises with solutions โ is on the part page.