Back to course

Nested Conditional Statements

Python Programming: The 0 to Hero Bootcamp

Nested Conditionals

Nesting means placing one if statement (or elif/else) inside another. This is necessary when the second decision depends entirely on the outcome of the first decision.

Example: Complex Eligibility Check

We check two layers of requirements: citizenship and age.

python citizenship = 'USA' age = 35

if citizenship == 'USA': print("Step 1: Eligible for US checks.")

# Nested If: This check only happens if the person is a USA citizen
if age >= 35:
    print("Step 2: Eligible for President (Age requirement met).")
else:
    print("Step 2: Too young to run for President.")
    

else: print("Ineligible: Must be a USA citizen.")

Avoiding Excessive Nesting

While necessary sometimes, too much nesting (known as 'callback hell' or 'pyramid of doom') makes code hard to read. Often, you can use the and operator to simplify nested if statements.

Nested (A bit messy):

python if condition1: if condition2: if condition3: # Execute...

Simplified (Better):

python if condition1 and condition2 and condition3: # Execute...