3.07 Nested Conditionals

Source lesson: python/nested-conditionals

Learning Objective: Use nested if statements when a decision should only be checked after an earlier condition has chosen a path, and test every path.

Popcorn Hack 1: After-School Homework Plan

Prediction (as given, is_weekday = True, homework_finished = False): prints Finish homework. Path: outer if is_weekday → inner else (homework not finished).

The loop below runs the same nested structure on every input combination so all three outcomes are tested.

Code Runner Challenge

Popcorn Hack 1 - Test the after-school homework plan

View IPYNB Source
# CODE_RUNNER: Popcorn Hack 1 - Test the after-school homework plan
for is_weekday in [True, False]:
    for homework_finished in [True, False]:
        print("weekday =", is_weekday, "| homework_finished =", homework_finished, "->", end=" ")
        if is_weekday:
            if homework_finished:
                print("Free time")
            else:
                print("Finish homework")
        else:
            print("Weekend plan")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
is_weekday homework_finished Outer branch Inner branch Message
True True if is_weekday if homework_finished Free time
True False if is_weekday else Finish homework
False either else (never checked) Weekend plan

On the weekend homework_finished doesn’t matter, because the inner check lives inside the weekday branch and is skipped.

Popcorn Hack 2: Repair the Student Account Check

Why the original isn’t nested: if has_permission: was at the same indentation as if logged_in:, so it ran even when the student wasn’t logged in. A logged-out student could still get “Page opened”. It also had no message for a logged-out student.

Fix: indent the permission check inside the logged-in branch and add an outer else.

Code Runner Challenge

Popcorn Hack 2 - Repair the student account check

View IPYNB Source
# CODE_RUNNER: Popcorn Hack 2 - Repair the student account check
tests = [(True, True), (True, False), (False, True)]

for logged_in, has_permission in tests:
    print("logged_in =", logged_in, "| has_permission =", has_permission)
    if logged_in:
        print("  Account found")
        if has_permission:
            print("  Page opened")
        else:
            print("  Permission needed")
    else:
        print("  Log in first")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Actual output: (True, True) → Account found, Page opened. (True, False) → Account found, Permission needed. (False, True) → Log in first. Even with has_permission = True, a logged-out student no longer gets the page.

Popcorn Hack 3: Lunch and Sports Practice

Code Runner Challenge

Popcorn Hack 3 - Test the lunch and sports-practice plan

View IPYNB Source
# CODE_RUNNER: Popcorn Hack 3 - Test the lunch and sports-practice plan
for lunch_packed in [True, False]:
    for practice_after_school in [True, False]:
        print("lunch_packed =", lunch_packed, "| practice =", practice_after_school, "->", end=" ")
        if lunch_packed:
            if practice_after_school:
                print("Eat your packed lunch and bring an extra snack for practice")
            else:
                print("Eat your packed lunch, no extra snack needed")
        else:
            if practice_after_school:
                print("Buy lunch and grab a snack for practice")
            else:
                print("Buy lunch at school")
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

All four recommendations print, one per combination.

JavaScript:

Code Runner Challenge

Homework Hack - Build a high school daily routine dashboard

View IPYNB Source
if (lunchPacked) {
    if (practiceAfterSchool) {
        console.log("Eat your packed lunch and bring an extra snack for practice");
    } else {
        console.log("Eat your packed lunch, no extra snack needed");
    }
} else {
    if (practiceAfterSchool) {
        console.log("Buy lunch and grab a snack for practice");
    } else {
        console.log("Buy lunch at school");
    }
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

College Board pseudocode:

IF (lunchPacked)
{
    IF (practiceAfterSchool)
    {
        DISPLAY("Eat your packed lunch and bring an extra snack for practice")
    }
    ELSE
    {
        DISPLAY("Eat your packed lunch, no extra snack needed")
    }
}
ELSE
{
    IF (practiceAfterSchool)
    {
        DISPLAY("Buy lunch and grab a snack for practice")
    }
    ELSE
    {
        DISPLAY("Buy lunch at school")
    }
}

Execution order: lunch_packed is checked first, and it picks which half runs. practice_after_school is checked second, inside whichever half was chosen. In Python indentation shows that ownership, in JavaScript and pseudocode the braces do, but the order is the same in all three.

Homework Hack: High School Daily Routine Dashboard

Structure: the outer account if / else comes first. Inside the logged-in branch there are two nested decisions: homework → practice, and lunch → practice. Possible recommendations:

Logged in Homework done Practice Homework / schedule recommendation
No — — Log in to see your dashboard (nothing else checked)
Yes No Yes Do homework at lunch / study hall before practice
Yes No No Finish homework before free time
Yes Yes Yes Head to practice after school
Yes Yes No Free time after school

Plus a meal line for logged-in students (packed lunch / buy lunch, with or without a practice snack).

# CODE_RUNNER: Homework Hack - Build a high school daily routine dashboard
student = {
    "logged_in": True,
    "homework_finished": False,
    "lunch_packed": True,
    "practice_today": True
}

def daily_dashboard(student):
    if student["logged_in"]:
        # nested decision 1: homework first, then practice
        if student["homework_finished"]:
            if student["practice_today"]:
                print("  Plan: Homework done, head to practice after school.")
            else:
                print("  Plan: Homework done, free time after school.")
        else:
            if student["practice_today"]:
                print("  Plan: Use lunch or study hall for homework, practice is after school.")
            else:
                print("  Plan: Finish homework before any free time.")

        # nested decision 2: meals, then practice
        if student["lunch_packed"]:
            if student["practice_today"]:
                print("  Meal: Packed lunch, and pack an extra snack for practice.")
            else:
                print("  Meal: Packed lunch, you're set.")
        else:
            if student["practice_today"]:
                print("  Meal: Buy lunch and grab a snack before practice.")
            else:
                print("  Meal: Buy lunch at school.")
    else:
        print("  Log in to see your daily dashboard.")

# Starter data first
print("Starter student:")
daily_dashboard(student)

# Test every meaningful outcome
tests = [
    {"logged_in": False, "homework_finished": True,  "lunch_packed": True,  "practice_today": True},
    {"logged_in": True,  "homework_finished": True,  "lunch_packed": True,  "practice_today": True},
    {"logged_in": True,  "homework_finished": True,  "lunch_packed": False, "practice_today": False},
    {"logged_in": True,  "homework_finished": False, "lunch_packed": False, "practice_today": True},
    {"logged_in": True,  "homework_finished": False, "lunch_packed": True,  "practice_today": False},
]
for i, test in enumerate(tests, start=1):
    print("Test", i, test)
    daily_dashboard(test)

Tests: the starter student plus 5 test students reach all 4 plan messages, all 4 meal messages, and the logged-out message. Test 1 is logged out with everything else True and still only prints “Log in…”, which shows the inner checks are skipped.

Why the inner checks depend on the outer decisions: homework, meals and practice are personal schedule data, so they only make sense after the account check confirms who the student is. That’s why they live inside if student["logged_in"], and a logged-out student never reaches them. Inside that branch, what to do with after-school time depends on whether homework is done first, and the snack only matters if there’s practice. So practice is checked inside the homework and lunch branches rather than at the same level.