What Are Nested Conditionals?
"A conditional inside of a conditional. When we are inside a conditional, we assume that condition is true. Then we can continue to further refine our checks and make more decisions."
The Concept: Narrowing Down
First Decision: Is it raining?
IF raining = True
Second Decision:
IF have_umbrella: walk
ELSE: stay_home
ELSE (not raining)
Just walk outside!
Code Structure
if condition1:
# First level decision
print("Condition 1 is true")
if condition2:
# Second level - NESTED inside first
print("Both conditions true!")
else:
print("Only condition 1 true")
else:
print("Condition 1 is false")
Key Insight: Each level of nesting adds another layer of indentation. The deeper the indent, the more conditions must be True to reach that code.
Interactive Example: Access Control
Real Example: Age and Permission Check
age = 16
has_permission = True
if age >= 18:
# Adult - can decide alone
print("Access granted (adult)")
else:
# Not adult - need to check permission
if has_permission:
print("Access granted (with permission)")
else:
print("Access denied (no permission)")
"Nested conditionals let you make refined decisions. First, check the big picture. Then, within each case, check the details."
Mental Model: Think of nested conditionals like a security checkpoint with multiple gates. You only reach the inner gates if you pass the outer ones first.