University of Free Knowledge
QA 76.73 · fol. 6

Choosing Which Lines Run

An if / elif / else statement runs exactly one branch, chosen by the first boolean test that comes out True. · 12 min

A boolean expression answers a question; an if statement acts on the answer. It reads a test, and when the test is True it runs the indented lines beneath it — otherwise it skips them. Add elif (else-if) branches to offer more tests, and a final else to catch everything left over. The iron rule: Python checks the tests from top to bottom, runs the block under the first one that is True, then leaves the whole statement. Exactly one branch runs, never two.

Guess before you learn

Suppose x is 5. The code tests if x > 0: first, then elif x > 3:. Both tests are true for 5. Which branch runs?

THE DEPTH DIAL — the same idea, younger or deeper
9–12

9–12

Order matters when tests overlap. If you check score >= 60 before score >= 90, the second can never fire — the first catches every high score first. Put the most specific or highest tests earliest. A chain of separate if statements differs from one if / elif chain: separate ifs each get evaluated, so several can run; an elif chain runs at most one.

else is optional. Without it, an if / elif chain can finish having run no branch at all, if every test was false. When you need a guaranteed fallback — some branch that always runs — supply the else.

branch

One of the blocks in an if / elif / else statement. At most one branch runs each time the statement is reached.

TrueFalseTrueFalsescore >= 90 ?grade = 'A'score >= 80 ?grade = 'B'grade = 'C' (else)
PLATE I A grade chain: each test that fails passes control down to the next.
Retrieval Gate — answer before you continue 0 / 4

1.An if / elif / else chain with an else is reached. How many of its branches run?

2.x is 3. if x > 5: print('a') / elif x > 1: print('b') / else: print('c'). What is printed?

3.A chain checks if n > 0: first, then elif n > 100:. Why can the second branch never run?

4.In one sentence, what does the else branch do, and when does it run?

The tests in a chain are just the boolean expressions from the last folio, now put to work. To predict what a chain does, you trace it: read the value of each variable, evaluate each test in turn, and follow the first one that is True. When several tests could be true, only their order decides the outcome — which is exactly where careful reading pays off.

Ink That Thinks — guess first; the answer draws itself.
Given temp = 30, drag the steps Python takes through this chain into the order it performs them: if temp < 0: / elif temp < 20: / elif temp < 40: 'warm' / else:.

  1. Test temp < 0, which is False, so skip this branch
  2. Test temp < 20, which is False, so skip this branch
  3. Test temp < 40, which is True, so run this branch
  4. Print 'warm' and leave the whole statement
Reorder, then commit.
PLATE II Tracing an if / elif / else chain: top to bottom, stop at the first True.

Trace this chain with `n = 7` — the steps fade as you master them

1
Start: n is 7. Evaluate the first test, n < 0.
n < 0 -> False
2
First test failed, so try the next: n == 0.
n == 0 -> False
3
Still false. Try the next: n < 10.
n < 10 -> True
4
First True test wins. Which line runs?
print('small positive')
Why is this true?

Why does putting a broad test like x > 0 before a narrow one like x > 100 make the narrow branch unreachable?

Python runs the first branch whose test is True and then stops. Every value that passes x > 100 also passes x > 0, so the broad test always fires first and the narrow branch never gets a turn. Order specific tests before general ones.

Retrieval Gate — answer before you continue 0 / 4

1.score = 72. if score >= 90: g='A' / elif score >= 70: g='B' / elif score >= 50: g='C' / else: g='F'. What is g?

2.Put these lines in the correct order to classify a number as negative, zero, or positive.

  1. if n < 0: print('negative')
  2. elif n == 0: print('zero')
  3. else: print('positive')

3.What is the difference between three separate if statements and one if / elif / elif chain?

4.In one sentence, explain why exactly one branch runs in an if / elif / else statement that has an else.

An if chooses whether a block runs; elif and else extend that into a clean pick-exactly-one decision. You now have tests and the machinery to act on them. But a program that runs each line only once is limited. The next unit introduces repetition: the while loop, which runs a block again and again for as long as a test stays True.

Practice — new ink and old, interleaved

1.Evaluate 10 % 3, the remainder of 10 divided by 3.

2.Which grouping does Python use for not True and False?

3.(4 < 2) or not (3 == 3) evaluates to?

4.Match each operator to its meaning.

==
!=
>=
not

5.Review from folio 1: put these lines in the order they run.

  1. print("Ready?")
  2. answer = input()
  3. print("Go!")

6.Review from folio 2: after x = 6 then x = x + x, what is the value of x?

7.x = 0. if x: print('yes') / else: print('no'). What is printed?

8.Order the tests as Python evaluates them for grade = 85 in a chain checking >= 90, then >= 80, then else.

  1. Test 85 >= 90, which is False
  2. Test 85 >= 80, which is True
  3. Assign 'B' and stop

9.Without looking back: in an if / elif / else chain, which branch runs, and what does else do?

The Call Slip — search everything Ctrl·K / ⌘K