intermediate

Nested Conditionals

Master complex decision-making with nested if statements in Python.

Nested conditionals allow you to make decisions within decisions. This is essential for handling complex logic where multiple factors influence the outcome. While powerful, nested conditionals should be used carefully to maintain readable code. This exercise teaches you when and how to use nested if statements effectively.

📚 Concepts & Theory

What are Nested Conditionals?

A nested conditional is an if statement inside another if statement.

age = 25
has_license = True

if age >= 18:
if has_license:
print("You can drive")
else:
print("Get a license first")
else:
print("Too young to drive")

When to Use Nested Conditionals:

  • When one condition only matters if another is true
  • When building decision trees
  • When handling multiple related checks
Alternative: Combining Conditions

Sometimes you can avoid nesting with logical operators:

if age >= 18 and has_license:
    print("You can drive")

Best Practices:

  • Limit nesting to 2-3 levels maximum
  • Consider using early returns to reduce nesting
  • Use meaningful variable names for conditions

🎯 Your Challenge

Write a program to determine ticket pricing. Given `age = 15` and `is_student = True`: if age is under 12, set `price` to 5. If age is 12-17, check if they are a student - students pay 8, non-students pay 10. If 18 or older, set price to 15.

📝 Starter Code

Python
# Customer info
age = 15
is_student = True

# Determine price using nested conditionals
if age < 12:
    price = 
elif age < 18:
    if is_student:
        price = 
    else:
        price = 
else:
    price = 
  • Check age < 12 first for children
  • Use elif for age < 18 (teens)
  • Nest the is_student check inside the teen block
  • Each block needs proper indentation

Solution

Python
age = 15
is_student = True

if age < 12:
    price = 5
elif age < 18:
    if is_student:
        price = 8
    else:
        price = 10
else:
    price = 15

Explanation

We first check if age is under 12 (child pricing). If not, we check if under 18 (teen). Within the teen bracket, we nest another if to check student status. Finally, else catches all adults 18+.

⚠️ Common Mistakes to Avoid

  • Wrong age boundary conditions
  • Forgetting the inner else block
  • Incorrect indentation of nested blocks
  • Using elif instead of nested if when needed

❓ Frequently Asked Questions

Try to limit nesting to 2-3 levels. Deeper nesting makes code hard to read. Consider refactoring into functions or using early returns.
Not always. Nesting is better when you need different actions for each branch, while combined conditions work best for a single result.

🔗 Related Concepts