Nested Conditions

Control Flow

Nested Conditions

In this tutorial, we'll place decisions inside other decisions.

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

logged_in = True
is_admin = False

if logged_in:
    if is_admin:
        print("Admin area")
    else:
        print("Normal account")
else:
    print("Please sign in")

Nested conditions are useful when one decision only matters after another decision is true.

Reading Nested Code

Read from the outside in:

1. Is the user logged in? 2. If yes, are they an admin? 3. If no, ask them to sign in

Indentation shows the structure.

Avoiding Unnecessary Nesting

Sometimes and is cleaner:

if logged_in and is_admin:
    print("Admin area")

This is easier when you only care about one combined condition.

Use nesting when each level has its own different outcome.

Keep Nesting Shallow

Nested code can become hard to read if it goes too deep. If you find yourself indenting many times, pause and ask whether a combined condition would be clearer.

Harder to read:

if logged_in:
    if is_member:
        if total > 30:
            print("Discount")

Often clearer:

if logged_in and is_member and total > 30:
    print("Discount")

Example: Discount

is_member = True
total = 35

if is_member:
    if total >= 30:
        print("Large member discount")
    else:
        print("Small member discount")
else:
    print("No member discount")

Practice

Write nested conditions for a game: if the player is alive, check whether they have a key. If they have a key, print "Door opened".