Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Nested Conditionals
Nested conditionals are if/else statements inside other if/else statements. Use them when decisions depend on multiple levels of criteria. However, try to keep nesting shallow (2-3 levels max) for readability.
Nested Conditionals
# Nested if-else example
age = 25
has_ticket = True
is_vip = False
if age >= 18:
if has_ticket:
if is_vip:
print("Welcome to the VIP section!")
else:
print("Welcome! Enjoy the show.")
else:
print("You need a ticket to enter.")
else:
print("Sorry, this event is 18+.")
# Cleaner approach: combine conditions
if age >= 18 and has_ticket and is_vip:
print("VIP access granted!")
elif age >= 18 and has_ticket:
print("General admission.")
elif age >= 18:
print("Buy a ticket first.")
else:
print("Must be 18+.")Tip
Tip
Flatten nested conditionals by combining with 'and'. if age >= 18 and has_ticket: is cleaner than nesting two if statements.
Python checks each condition in order - the first True branch runs, then it exits
Common Mistake
Warning
Deeply nested conditionals (3+ levels) are a code smell. Refactor using combined conditions or guard clauses.
Practice Task
Note
Refactoring challenge: (1) Write a 3-level nested if. (2) Refactor it using combined 'and' conditions. (3) Compare readability.