Python · Stage 3 – Making Decisions · Lesson 22 of 50

Nested if Statements

Place one small decision inside another decision.

has_account = True
password_ok = True
if has_account:
    if password_ok:
        print("Welcome")
Line-by-line explanation
  1. Two facts are stored.
  2. The outer if first checks for an account.
  3. The inner if is indented inside the outer block.
  4. Welcome appears only when both checks succeed.

Use nesting when the second question only makes sense after the first. For two simple facts, and may be clearer.

Tiny Practice

Show “Discount applied” only for a member who also has a coupon.

Starter template

is_member = True
has_coupon = True
if is_member:
    CHANGE_ME
Line-by-line explanation
  1. The member check is outer.
  2. The coupon check belongs inside it.
Hint
  1. Indent another if.
  2. Check has_coupon.
  3. Indent the print line twice.
Show Solution
is_member = True
has_coupon = True
if is_member:
    if has_coupon:
        print("Discount applied")
Line-by-line explanation
  1. The outer check succeeds.
  2. The inner check then succeeds.
  3. The message is displayed.