Worked examples — Nested conditionals
Before we start, three plain-word reminders (so no symbol is unearned):
if condition:means "==only run the indented block below me ifconditionis True==".else:means "run me when the matchingifwas False". See Conditional statements (if-elif-else).- Indentation = how far a line is pushed right with spaces. That push decides which
ifowns 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.

Ex 1 — Cell A: both gates True
- Check the outer gate.
temperature >= 38→39 >= 38→True. Why this step? Nothing indented under the outerifeven exists to Python until this passes — the outer gate is asked first, always. - Enter the inner block. Because outer is True, the inner
if has_fever:is now reached.has_feverisTrue. Why this step? We are inside the outer body, so the inner question is finally "askable". - Take the inner
ifbranch. Print"See a doctor". Why this step? Inner True → its own block runs, itselseis 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
- Outer gate.
39 >= 38→True, enter outer body. Why this step? Outer decides whether the inner gate is even reached; here it opens. - Inner gate.
has_feverisFalse. Why this step? We're past the outer gate, so the inner boolean now controls the result. - Take the inner
else. Print"Just warm". Why this step? Inner False → skip the innerifblock, run the innerelse(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
- Outer gate.
36 >= 38→False. Why this step? This is the whole trap: the outer gate fails. - Skip the ENTIRE outer body. Everything indented under the outer
if— including the innerif has_fever:— is jumped over. Why this step? Python never evaluates code inside a block whoseifwas False;has_feverbeing True is irrelevant because that line is never reached. - Take the outer
else. Print"Normal". Why this step? The outerelsematches the outerif(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)
- Outer gate uses
>=, not>.0 >= 0→True. Why this step? The choice of>=(see Comparison operators) is deliberate: it includes the boundary in the "non-negative" branch, so0enters the outer body instead of falling toelse. - Inner equality check.
n == 0→0 == 0→True. 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. - 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,0would wrongly printnegative. The degenerate input catches that bug. ✅
Ex 5 — Cell E: limiting / extreme magnitude
- Outer gate.
-1000000 >= 0→False, so we enter the outerelse. Why this step? Big magnitude doesn't matter to the sign test — only the sign ofnpicks the outer branch. - Inner magnitude gate. Now inside the negative case:
n < -100→-1000000 < -100→True. 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". - 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: asn → -∞it staysvery negative; asnclimbs toward-100it would flip tomildly negativeatn = -100(since-100 < -100is False). ✅
Ex 6 — Cell F: real-world word problem (login → role)
- 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). - Outer gate.
logged_inisTrue→ enter. Why this step? Only logged-in visitors get a role question; asking "is a stranger an admin?" is meaningless. - Inner gate.
is_adminisFalse→ innerelse→page = "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
- Evaluate Version A.
age >= 18→20 >= 18→True; innerhas_license→True→result_A = "Can drive". Why this step? Walk the nest to its leaf as usual. - Evaluate Version B.
age >= 18 and has_license→True and True→True→result_B = "Can drive". Why this step?andis True only when both operands are True — exactly the "both gates" condition. It collapses two gates into one line (see Boolean logic and operators). - 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
- Find the
else's partner by indentation. Theelseis indented at the same level asif a > 0:, not asif b > 0:. Why this step? Python pairselsewith the nearest unmatchedifat its own indentation — the golden rule from Indentation in Python. So thiselsebelongs to the outerif, even though it visually sits under the inner one. - Outer gate.
a > 0→-3 > 0→False. Why this step? Outer False means we skip its whole body (the innerif b > 0:is never reached, even thoughb > 0is True — a decoy just like Ex 3). - Take the outer
else.label = "a not positive". Why this step? Outer False → outerelseruns.
Verify: Path = cell H.
label == "a not positive". Trap check: a careless reader expectselseto pair withif b > 0and predicts nothing runs — but indentation overrules eyesight. ✅ To make theelseattach to the innerif, 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/elsegrammar every cell uses. - Comparison operators —
>=,==,<that set each gate (crucial in cells D/E). - Boolean logic and operators —
andfor 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).