← All lessons

Nested conditions

Sign in · Sign up

Lesson 2.6

An if can sit inside another if: first check one thing, then check the second inside it.

if age >= 12:
    if day == "saturday":
        print("You get the discount")

Each nesting level shifts right by 4 more spaces — you get a little staircase. The inner if is checked only when the outer condition is true.

age and day are set by the check. The program prints:

  • You get the discount — if the age is 12 or more and the day is "saturday";
  • No discount — if the age is 12 or more but the day is different;
  • No access — if the age is under 12.
Hint

First the outer if on age, inside it an if/else on the day.

The nested if has an indent 4 more spaces: otherwise Python thinks it is no longer inside the first one. Each level ends with its own colon.