Lesson 7 of 21 · 2 min
Nested if — An if Inside Another if
The WHY — Why Nest if Statements?
Sometimes a decision depends on multiple independent conditions that need to be checked in sequence. For example: a website first checks if you are 18+, then separately checks if you have an account. Both must be checked independently.
age = 20 # person's age
has_id = True # whether they have a valid ID card
if age >= 18: # first check: are they old enough?
if has_id: # second check (inside first): do they have ID?
print("Entry allowed") # both conditions passed
else:
print("Need a valid ID") # old enough but no ID
else:
print("Too young for entry") # first check failed — didn't even check ID
Output: Entry allowed
Warning: Deeply nested ifs (if inside if inside if inside if) become very hard to read. More than 2-3 levels usually means you need to redesign your logic.
