Nested Conditionals
Overview
Learn how to write conditionals inside other conditionals to create more precise and layered logic. This section focuses on keeping nested code readable while managing multiple logical checks.
What You Will Learn in This Lesson
By the end of this lesson, you will know:
- What nested conditionals are: Understand how to put if statements inside other if statements.
- Why nesting is useful: Learn when and why you'd want to nest conditionals.
- How indentation works: Master the indentation rules for nested code blocks.
- Keeping code readable: Learn best practices for writing clear nested conditionals.
Why This Matters
Sometimes you need to make decisions based on multiple conditions. Nested conditionals let you check conditions inside other conditions, like asking "If this is true, then check if that is also true." This creates more precise logic for complex situations.
Step 1: What Are Nested Conditionals?
A nested conditional is an if statement (or if-else, if-elif-else) that appears inside another if statement. Think of it like Russian nesting dolls - one conditional inside another. This lets you check multiple conditions in a structured way.
if outer_condition:
# This code runs if outer_condition is True
if inner_condition:
# This code runs if BOTH conditions are True
print("Both conditions are true!")
Start with the Outer if
Write your first if statement with its condition. This is the "outer" conditional - it's checked first.
if age >= 18:
# Outer if block starts here
Add the Inner if
Inside the outer if block (indented), write another if statement. This is the "inner" or "nested" conditional.
if age >= 18:
if has_license:
# Inner if block - indented twice!
Indent Properly
The inner if must be indented inside the outer if. Code inside the inner if must be indented even more (8 spaces total, or 2 levels of indentation).
if age >= 18: # 0 spaces
if has_license: # 4 spaces (inside outer if)
print("Can drive") # 8 spaces (inside inner if)
Key Concept: For code inside a nested if to run, BOTH conditions must be True. First, the outer condition must be True. Only then does Python check the inner condition. If the outer condition is False, Python never even looks at the inner condition - it skips the entire outer block.
Mini Practice #1: Your First Nested Conditional
Try It YourselfTry this nested conditional. Notice how both conditions must be True for the inner code to run:
What happened? Python first checked the outer condition: age >= 18. Since age is 20, this was True, so Python entered the outer if block and printed "You are an adult." Then, still inside the outer if block, Python checked the inner condition: has_license. Since has_license is True, Python entered the inner if block and printed "You can drive!" Notice that both messages printed because both conditions were True. Try changing has_license to False - you'll see only "You are an adult." prints, because the inner condition becomes False.
Step 2: Why Use Nested Conditionals?
Nested conditionals are useful when you need to check conditions in a specific order, or when one condition only matters if another condition is already True.
When Order Matters
Sometimes you need to check one thing before checking another. For example, you can only check if someone can drive if they're already an adult.
if age >= 18:
if has_license:
print("Can drive")
else:
print("Adult but no license")
More Precise Logic
Nesting lets you create more specific conditions. Instead of checking everything at once, you check step by step.
if is_raining:
if have_umbrella:
print("Go outside")
else:
print("Stay inside")
Real-World Example: Movie Ticket Pricing
Imagine a movie theater with these rules: Children (under 12) get a discount, but only if they're with an adult. Adults pay full price. Seniors (65+) get a discount. You could write this with nested conditionals:
if age < 12:
if with_adult:
price = 5 # Child discount
else:
price = 10 # No discount without adult
elif age >= 65:
price = 7 # Senior discount
else:
price = 10 # Full price
This structure makes it clear that the "with adult" check only matters for children.
Step 3: Understanding Indentation Levels
Indentation is crucial for nested conditionals. Each level of nesting requires another level of indentation. Python uses indentation to understand which code belongs to which conditional.
# Level 0: No indentation (main code)
age = 20
has_license = True
if age >= 18: # Level 0: Outer if
print("Adult") # Level 1: Inside outer if (4 spaces)
if has_license: # Level 1: Inner if (4 spaces)
print("Can drive") # Level 2: Inside inner if (8 spaces)
else: # Level 1: Inner else (4 spaces)
print("No license") # Level 2: Inside inner else (8 spaces)
else: # Level 0: Outer else (0 spaces)
print("Minor") # Level 1: Inside outer else (4 spaces)
Level 0: Main Code
Code at the main level has no indentation. This includes variable assignments and the outer if/else statements.
Level 1: Inside Outer Conditional
Code inside the outer if/else is indented 4 spaces. This includes the inner if statement itself.
Level 2: Inside Inner Conditional
Code inside the inner if/else is indented 8 spaces (two levels). This is the deepest level in this example.
Remember: Python is very strict about indentation. All code at the same logical level must have the same indentation. If you mix spaces and tabs, or have inconsistent spacing, Python will give you an error. Most Python programmers use 4 spaces per indentation level.
Mini Practice #2: Multiple Levels of Nesting
Try It YourselfTry this example with multiple levels. Pay attention to the indentation:
What happened? Python first checked if temperature > 80. Since temperature is 85, this was True, so Python entered the outer if block and printed "It's hot!" Then, still inside the outer if block, Python checked if is_summer is True. Since it is True, Python entered the inner if block and printed "Perfect for swimming!" Notice how the inner else block was skipped because the inner if condition was True. Try changing is_summer to False to see the inner else block execute instead.
Step 4: Nested if-else Structures
You can nest any type of conditional structure. You can have if-else inside if, if-elif-else inside if, or even multiple levels of nesting.
age = 20
has_license = True
has_insurance = False
if age >= 18:
print("You are an adult.")
if has_license:
print("You have a license.")
if has_insurance:
print("You can drive legally!")
else:
print("You need insurance to drive.")
else:
print("You need a license to drive.")
else:
print("You are a minor.")
How Python Evaluates This
Python evaluates nested conditionals from outside to inside:
- First, it checks
age >= 18. If False, it goes to the outer else. - If True, it enters the outer if block and checks
has_license. - If has_license is True, it enters that if block and checks
has_insurance. - Only if all three conditions are True does the innermost code run.
This creates a "decision tree" where each level narrows down the possibilities.
Step 5: When NOT to Use Nested Conditionals
While nested conditionals are powerful, sometimes there are better alternatives. Knowing when to use them and when to avoid them makes your code cleaner.
✅ Good: When Order Matters
Use nesting when one check only makes sense after another check passes.
if age >= 18:
if has_license:
print("Can drive")
Makes sense: can't check license if not adult
❌ Avoid: When You Can Use and
If both conditions are independent, use and instead of nesting.
# Instead of nesting:
if age >= 18:
if has_license:
print("Can drive")
# Use and:
if age >= 18 and has_license:
print("Can drive")
Simpler and easier to read
Best Practice: Use nested conditionals when the inner condition only matters if the outer condition is True. Use and when both conditions are equally important and independent. Generally, if you can use and instead of nesting, do it - it's simpler and easier to read.
End-of-Lesson Exercises
Exercise 1: Write a Nested Conditional
Create variables: age = 20 and has_license = True. Write a nested conditional that first checks if age >= 18, and if true, checks if has_license is True. If both are true, print "You can drive!".
Use an outer if to check age, then an inner if to check has_license. Make sure to indent properly.
Exercise 2: Nested if-else
Create variables: temperature = 85 and is_summer = True. Write a nested conditional: if temperature > 80, then check if is_summer is True. If it's summer, print "Perfect for swimming!", otherwise print "Unusual heat for this season."
Use an outer if for temperature, then an inner if-else for is_summer.