1.2.16 · D3Introduction to Programming (Python)

Worked examples — Nested conditionals

2,379 words11 min readBack to topic

Before we start, three plain-word reminders (so no symbol is unearned):

  • if condition: means "==only run the indented block below me if condition is True==".
  • else: means "run me when the matching if was False". See Conditional statements (if-elif-else).
  • Indentation = how far a line is pushed right with spaces. That push decides which if owns the line — see Indentation in Python.

The scenario matrix

A two-gate nested conditional has an outer gate (True / False) and, inside each outer outcome, an inner gate (True / False). That already gives four leaf paths. On top of that we must cover degenerate inputs (values sitting exactly on a boundary like n == 0), a short-circuit / never-checked case, a word problem, and an exam-style dangling-else twist.

Cell Outer gate Inner gate What it tests Worked in
A True True both gates pass Ex 1
B True False outer passes, inner fails Ex 2
C False (never checked) inner is skipped entirely Ex 3
D boundary value equals branch degenerate input == 0 Ex 4
E limiting value extreme branch very large / edge magnitude Ex 5
F word problem login → role real-world sequential decision Ex 6
G flatten choice and vs nest when to collapse depth Ex 7
H dangling-else indentation trap exam-style misattachment Ex 8

The map below shows the four leaf paths (cells A–C, plus the True/inner-True leaf) so you can see the table as a tree, not just rows.

Figure — Nested conditionals

Ex 1 — Cell A: both gates True

  1. Check the outer gate. temperature >= 3839 >= 38True. Why this step? Nothing indented under the outer if even exists to Python until this passes — the outer gate is asked first, always.
  2. Enter the inner block. Because outer is True, the inner if has_fever: is now reached. has_fever is True. Why this step? We are inside the outer body, so the inner question is finally "askable".
  3. Take the inner if branch. Print "See a doctor". Why this step? Inner True → its own block runs, its else is skipped.

Verify: Path taken = outer-True → inner-True = cell A. Output: See a doctor. Sanity: a hot patient with fever should indeed be told to see a doctor. ✅


Ex 2 — Cell B: outer True, inner False

  1. Outer gate. 39 >= 38True, enter outer body. Why this step? Outer decides whether the inner gate is even reached; here it opens.
  2. Inner gate. has_fever is False. Why this step? We're past the outer gate, so the inner boolean now controls the result.
  3. Take the inner else. Print "Just warm". Why this step? Inner False → skip the inner if block, run the inner else (the one indented at the inner level, per Indentation in Python).

Verify: Path = outer-True → inner-False = cell B. Output: Just warm. Sanity: hot but no fever → warm, not doctor. ✅ Notice cells A and B differ only by the inner gate, exactly what nesting is for (different message per level).


Ex 3 — Cell C: outer False, inner never checked

  1. Outer gate. 36 >= 38False. Why this step? This is the whole trap: the outer gate fails.
  2. Skip the ENTIRE outer body. Everything indented under the outer if — including the inner if has_fever: — is jumped over. Why this step? Python never evaluates code inside a block whose if was False; has_fever being True is irrelevant because that line is never reached.
  3. Take the outer else. Print "Normal". Why this step? The outer else matches the outer if (same indentation), so it runs when the outer gate is False.

Verify: Path = outer-False → inner-not-evaluated = cell C. Output: Normal. This is the parent note's "no ticket, no passport check". The inner truth value was a decoy. ✅


Ex 4 — Cell D: degenerate boundary input (== 0)

  1. Outer gate uses >=, not >. 0 >= 0True. Why this step? The choice of >= (see Comparison operators) is deliberate: it includes the boundary in the "non-negative" branch, so 0 enters the outer body instead of falling to else.
  2. Inner equality check. n == 00 == 0True. Why this step? Once inside, we split the non-negatives into the degenerate case (0) versus strictly positive. Zero needs its own message, which is a textbook reason to nest.
  3. Take the inner if. Print "zero". Why this step? Inner True runs its block.

Verify: Path = cell D (boundary). Output: zero. Boundary check: if we'd used > in the outer gate, 0 would wrongly print negative. The degenerate input catches that bug. ✅


Ex 5 — Cell E: limiting / extreme magnitude

  1. Outer gate. -1000000 >= 0False, so we enter the outer else. Why this step? Big magnitude doesn't matter to the sign test — only the sign of n picks the outer branch.
  2. Inner magnitude gate. Now inside the negative case: n < -100-1000000 < -100True. Why this step? Inside a known-negative value, we ask a second question about how extreme it is. Nesting encodes "classify magnitude only after confirming it's negative".
  3. Take inner if. Print "very negative". Why this step? Inner True runs.

Verify: Path = outer-False → inner-True = cell E. Output: very negative. Limiting sanity: as n → -∞ it stays very negative; as n climbs toward -100 it would flip to mildly negative at n = -100 (since -100 < -100 is False). ✅


Ex 6 — Cell F: real-world word problem (login → role)

  1. Translate the words into gates. "if logged in, then check admin" is literally an outer gate (logged_in) with an inner gate (is_admin). Why this step? The dependency "ask admin only after login succeeds" is a sequential-dependent decision — nesting's home turf (see Boolean logic and operators).
  2. Outer gate. logged_in is True → enter. Why this step? Only logged-in visitors get a role question; asking "is a stranger an admin?" is meaningless.
  3. Inner gate. is_admin is False → inner elsepage = "home". Why this step? Passed the login gate, failed the admin gate.

Verify: Path = cell F (= structurally cell B). page == "home". Sanity: a signed-in non-admin lands on the home page, never the login screen. ✅


Ex 7 — Cell G: nest vs flatten with and

  1. Evaluate Version A. age >= 1820 >= 18True; inner has_licenseTrueresult_A = "Can drive". Why this step? Walk the nest to its leaf as usual.
  2. Evaluate Version B. age >= 18 and has_licenseTrue and TrueTrueresult_B = "Can drive". Why this step? and is True only when both operands are True — exactly the "both gates" condition. It collapses two gates into one line (see Boolean logic and operators).
  3. Compare and decide. result_A == result_B == "Can drive". Why this step? Because every "No" branch produces the same single outcome, there's no distinct per-level message — so Code readability and refactoring says flatten. Keep the nest only if the "too young" and "no license" cases needed different messages.

Verify: Path = cell G. Both give "Can drive"; the two forms are logically identical for a single-outcome AND. ✅


Ex 8 — Cell H: exam-style dangling-else twist

  1. Find the else's partner by indentation. The else is indented at the same level as if a > 0:, not as if b > 0:. Why this step? Python pairs else with the nearest unmatched if at its own indentation — the golden rule from Indentation in Python. So this else belongs to the outer if, even though it visually sits under the inner one.
  2. Outer gate. a > 0-3 > 0False. Why this step? Outer False means we skip its whole body (the inner if b > 0: is never reached, even though b > 0 is True — a decoy just like Ex 3).
  3. Take the outer else. label = "a not positive". Why this step? Outer False → outer else runs.

Verify: Path = cell H. label == "a not positive". Trap check: a careless reader expects else to pair with if b > 0 and predicts nothing runs — but indentation overrules eyesight. ✅ To make the else attach to the inner if, you'd indent it deeper.


Recall Every cell, one line each

Cell A (both True) ::: run inner if block Cell B (outer True, inner False) ::: run inner else Cell C (outer False) ::: skip whole outer body, inner never evaluated, run outer else Cell D (n == 0 on >= boundary) ::: enters non-negative branch, prints zero Cell E (extreme negative) ::: outer else then inner True → very negative Cell H (dangling else) ::: else pairs with the if at its own indentation, not the visually-closest one


Connections

  • Parent: Nested conditionals — the shape these examples exercise.
  • Conditional statements (if-elif-else) — the if/else grammar every cell uses.
  • Comparison operators>=, ==, < that set each gate (crucial in cells D/E).
  • Boolean logic and operatorsand for the flatten decision in cell G.
  • Indentation in Python — the rule that resolves the cell-H dangling-else.
  • Code readability and refactoring — when to collapse a nest (cell G).

Scenario tree

True

False

True

False

Two-gate nested if

Outer gate

Inner gate reached

Cell C outer else runs

Cell A inner if runs

Cell B inner else runs

Edge inputs

Cell D value equals zero

Cell E extreme magnitude

Indentation twist

Cell H else pairs with outer if