1.2.16 · D2Introduction to Programming (Python)

Visual walkthrough — Nested conditionals

1,878 words9 min readBack to topic

We follow this exact code the whole way down. Read it, but don't try to understand it yet — we will earn every line:

n = -7
if n >= 0:
    if n == 0:
        print("zero")
    else:
        print("positive")
else:
    if n < -10:
        print("very negative")
    else:
        print("negative")

Step 1 — What "indent" even means (the invisible ruler)

WHAT. Before any logic, look at where each line starts. Some lines begin at the far left. Some are pushed to the right by spaces. That horizontal push is called indentation.

WHY this first. In most languages, brackets { } group code. In Python there are no brackets — indentation *is* the grouping. So the very first thing your eye must learn to read is the left edge of each line, because that edge alone decides which if owns which line. If you can't see the edge, you can't predict the output.

PICTURE. Each line sits on a vertical "shelf." Shelf 0 is the far left, shelf 1 is one step in, shelf 2 is two steps in. The red line marks shelf 0 — the ground floor.

Figure — Nested conditionals

Step 2 — What a single if is: a fork with one gate

WHAT. Take the outer line by itself: if n >= 0:. This is a condition — a yes/no question — followed by a colon :. Everything indented under it (on the next shelf in) is the "body": the code that runs only if the answer is yes.

WHY. Before we nest two gates, we must be certain what one gate does. A single if is a fork in a path: the question splits the road into a "True road" (enter the body) and a "False road" (skip the body, or take the else). Nesting is nothing but putting another fork on the True road.

PICTURE. The red diamond is the question n >= 0. One arrow leaves labelled True, one labelled False.

Figure — Nested conditionals

Step 3 — Nesting: a second fork sitting on the True road

WHAT. Now put a whole second if/else inside the body of the first. In our code, on shelf 1 (inside the outer True branch) sits if n == 0: with its own else. That inner fork is only reachable by first travelling the outer True road.

WHY. This is the entire point of the parent topic. The inner question n == 0 is meaningless unless we already know n >= 0. Nesting encodes "ask B only after A said yes." Geometrically: the inner diamond is downstream of the outer True arrow — you physically cannot reach it any other way.

PICTURE. Two diamonds. The red one is the inner fork; notice it hangs off the True arrow of the outer fork. The False arrow of the outer fork never touches it.

Figure — Nested conditionals

Step 4 — Both branches nest: the full four-leaf tree

WHAT. Our real code nests on both sides: the outer else also contains an inner if n < -10: / else. So there are four possible ending rooms: zero, positive, very negative, negative.

WHY. We must cover every case — a reader should never hit an input we didn't show. Two forks, each two-way, give leaves. Listing all four proves nothing was left dangling.

PICTURE. The complete tree. The red path is one specific journey (we walk it live in Step 5); the black paths are the three other possible endings, drawn so you can see nothing is missing.

Figure — Nested conditionals

Step 5 — Walk the machine with n = -7 (the live trace)

WHAT. Set n = -7 and let the marble roll down the tree. At each diamond we compute the yes/no and take the matching arrow.

WHY. A picture of all paths (Step 4) shows possibility; a trace shows actuality. This is how you predict output by hand — the skill the whole chapter is training.

The three questions at each step (WHAT we did / WHY / WHAT it looks like):

  1. Outer gate n >= 0-7 >= 0False. Why: is left of . → take the outer else arrow. The entire first branch (including its inner if n == 0) is skipped — the marble never even touches those diamonds.
  2. Inner gate (inside the else) n < -10-7 < -10False. Why: is to the right of on the number line, so it is not smaller. → take the inner else arrow.
  3. Land on the leaf print("negative"). Output: negative.

PICTURE. The red marble path lights up exactly the arrows taken: outer→False, inner→False, land on negative. The greyed diamond is the one Python never evaluated.

Figure — Nested conditionals

Step 6 — The dangling-else edge case (shelves decide the mate)

WHAT. Now the danger. Consider this different code, where the last else sits on shelf 0 instead of shelf 1:

if a > 0:
    if b > 0:
        print("both pos")
else:
    print("a not positive")

Your eye wants that else to pair with if b > 0. It does not.

WHY it matters. Python matches an else to the nearest unmatched if on the same shelf. The else here is on shelf 0, and the only unmatched if on shelf 0 is if a > 0. So it's the outer else. Python gives no error — your logic just silently runs wrong. This is why Step 1 (reading the left edge) was not optional.

PICTURE. Two vertical dashed shelf-lines. The else and if a > 0 share the same red shelf-line, so an arc connects them. The inner if b > 0 (on shelf 1) is left with no else.

Figure — Nested conditionals

Step 7 — The degenerate cases (empty gate, always-true, always-false)

WHAT. Three "boundary" inputs the reader must never be surprised by:

  • On the boundary: n = 0. Then n >= 0 is True (0 is ≥ 0), enter outer True, then n == 0 is True → prints zero. The boundary belongs to the True side because of the = in >=.
  • Always-False outer: if the outer condition can never be true, the entire nested block is dead code — the inner if is never even parsed for execution. This is the "no ticket, no passport" case from the parent.
  • Always-True outer with no else: a lone nested if with no else simply falls through and does nothing when False — no output, no error.

WHY. Boundaries (>= vs >) and empty branches are exactly where beginners get one-off wrong answers. Showing them closes every gap.

PICTURE. A number line with the single red point sitting on the boundary, an arrow showing it routes to the True side, and the two open rays ( and ) labelled with their destinations.

Figure — Nested conditionals
Recall

Where does n = 0 go, and why? ::: To the True branch, because >= includes equality; then the inner n == 0 catches it and prints zero. If the outer condition is always False, what happens to the inner if? ::: It is never reached or evaluated — it is effectively dead code.


The one-picture summary

Everything above compressed into a single decision tree for n, with the four leaves, the two shelf levels marked, and the red boundary point shown routing to the True side. This one image is the nested conditional.

Figure — Nested conditionals
Recall Feynman: the whole walkthrough in plain words

Picture a marble dropped into a set of chutes. The left edge of each line of code is an invisible shelf, and a line's shelf tells you which chute it lives in — that's all indentation means. The first chute asks a yes/no question (is n at least 0?). "Yes" rolls the marble onto a road that has another question waiting on it; "No" rolls it onto a different road with its own second question. Because the second questions sit downstream, they're only asked after the first is answered — you can't check "is n exactly 0?" on a marble that already fell down the negative road. We dropped n = -7: first question "at least 0?" → no, roll left; second question "below −10?" → no (−7 is bigger than −10), roll to the leaf that says negative. The one trap: an else pairs with the if on its own shelf, never the one your eye thinks is closest — so always read the left edge first. And the boundary marble n = 0 rolls to the "yes" side, because >= lets equal count as pass.


Connections

  • Parent topic — the concept this page derives visually.
  • Conditional statements (if-elif-else) — the single fork we nested.
  • Indentation in Python — the shelves in Steps 1 and 6.
  • Comparison operators>=, ==, < at every diamond.
  • Boolean logic and operators — how True/False choose the arrow.
  • Code readability and refactoring — keeping shelves clean to dodge the dangling else.