Python Nested If

A nested if is an if statement placed inside another if statement, letting a program ask follow-up questions only after an earlier condition has been met.

What nesting means

Sometimes a single condition is not enough to make a decision. You may first want to confirm one fact, and only then test a second, more detailed fact. Placing one if inside the body of another creates this layered logic, and each inner statement is reached only when its outer condition is true.

One if inside another

number = 42

if number >= 0:
    if number == 0:
        print("The number is zero.")
    else:
        print("The number is positive.")
else:
    print("The number is negative.")

In the example above, Python only checks whether the number equals zero after it has confirmed the number is not negative. The extra level of indentation is what tells Python that the inner if belongs to the outer one.

Note: Each level of nesting adds one more step of indentation. Keeping indentation consistent is essential, because it is the only thing that defines which block a statement belongs to.

A practical example

Nested conditions are common when a decision naturally happens in stages. Consider checking whether someone can enter an event: first they must have a ticket, and only then does their age determine which area they may access.

Staged checks

has_ticket = True
age = 16

if has_ticket:
    if age >= 18:
        print("Welcome to the main hall.")
    else:
        print("Welcome to the family section.")
else:
    print("Please buy a ticket first.")

When to nest and when not to

Nesting is powerful, but too many layers make code hard to read. If several conditions must all be true at the same time, it is usually clearer to combine them with the and operator on a single line instead of stacking if statements.

  • Prefer nesting when an inner test only makes sense after an outer test passes.
  • Prefer a combined condition, such as if has_ticket and age >= 18, when the tests are independent and both required.
  • Watch the indentation depth: more than two or three levels is a hint to refactor.
  • Returning early from a function can flatten deeply nested logic into simpler steps.
ApproachBest used whenReadability
Nested ifA later check depends on an earlier oneGood at shallow depth
Combined andMultiple independent checks must all passVery clear
elif chainOne of several mutually exclusive cases appliesVery clear
Note: If you find yourself indenting four or five levels deep, pause and ask whether the logic could be split into a helper function or rewritten with combined conditions.