🎓 A1Learner
🔍

Python Nested If

A nested if is an if statement placed inside another if statement. The inner if runs only when the outer condition is true.

An if inside an if

The inner test runs only after the outer test passes.

age = 20
has_ticket = True
if age >= 18:
    if has_ticket:
        print("You may enter")

The inner if can have its own else

Here the age test passes, but the member test fails.

age = 20
member = False
if age >= 18:
    if member:
        print("Member price")
    else:
        print("Full price")

The same idea with and

Both tests guard one outcome, so one flat line says it more clearly.

age = 20
has_ticket = True
if age >= 18 and has_ticket:
    print("You may enter")

Example

age = 10
member = True
if age < 13:
    print("Child ticket")
    if member:
        print("Price: 6 dollars")
    else:
        print("Price: 8 dollars")
else:
    print("Adult ticket")
    if member:
        print("Price: 10 dollars")
    else:
        print("Price: 12 dollars")

Key points

  • Nested: one block placed inside another block.
  • The inner if runs only when the outer condition is true.
  • Read nested code by its indent.
  • Each level lines up under its own if line.
  • Use and instead when both tests guard one single outcome.
  • Flat code is easier to read.

In this example, age is 10 and member is True. The outer test asks if age is under 13. It is, so the program prints "Child ticket". Inside that block, the inner test checks member. It is true, so the price line prints 6 dollars. The whole adult branch is skipped.

Note

Deep nesting gets hard to follow.

If you nest past two levels, look for an and test or an elif chain instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does this code print? age = 25 student = True if age >= 18: if student: print("Student discount") else: print("Regular price")