Course outline · 0% complete

0/32 lessons0%

Course overview →

if, elif, else

lesson 4-1 · ~11 min · 10/32

Recall from lesson 3-2 that input() returns the string "42" when the user types 42.

The call always hands back text, whatever the characters happen to look like, which is why lesson 3-2 wrapped it as int(input()) to obtain a number. That detail matters immediately here, because this unit's programs compare numbers, and comparing a string against a number does not give the result you want. Convert on the way in, then decide.

The full decision shape

Everything you have written so far runs the same lines on every run. Real programs earn their keep by deciding: is this password correct, does this order qualify for free shipping, which band does this score fall in. The if statement is how a program takes different paths for different data, and it appears in essentially every function you will ever read.

An if statement runs its indented block only when its condition is True. The complete shape has three parts:

score = 83
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")

elif means else if: checked only when everything above it was False. else catches whatever is left. Python tests the conditions top to bottom and runs exactly one branch, then jumps past the whole chain. That is why score >= 80 is safe as the second test: reaching it already proves the score is below 90.

Comparisons: == equal (two signs, = alone is assignment), != not equal, <, >, <=, >=. Indentation is not decoration in Python, the 4 spaces are how it knows what belongs to each branch.

score >= 90 ?score >= 80 ?score >= 70 ?FalseFalseABCTrueTrueTrueelse: Fscore = 83 takes the gold path: exactly one branch runs
An elif chain checks top to bottom. With score = 83, the first test fails, the second passes, branch B runs, the rest are skipped.

Following the grading chain

With score set to 83, only one of the four branches runs, and the trailing print shows where control lands afterwards.

score = 83
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")
print("done")

Output

B
done

Python tested score >= 90 first and got False, then score >= 80 and got True, so it printed B and jumped past the remaining elif and else entirely. The C test never ran, even though 83 is also above 70, which is precisely the behavior an elif chain guarantees. The final line is not indented, so it belongs to no branch and prints on every run.

Predicting the result for other values is a good check on that model: 95 stops at the first test and prints A, 71 falls through to the third and prints C, and 50 reaches the else and prints F.

A temperature chain works the same way, with the thresholds arranged from coldest upward so each test only needs a single comparison.

t = 3
if t < 0:
    print("freezing")
elif t < 15:
    print("cold")
elif t < 25:
    print("mild")
else:
    print("hot")

Output

cold

Order is what keeps these conditions simple. Reaching elif t < 15 already proves that t < 0 was False, so the range from 0 up to 15 is implied and no combined test is needed. Writing the checks in the other order would break that: a leading t < 25 would swallow freezing temperatures too, since every negative number is also below 25. With t at 3 the first test fails, the second succeeds, and the rest of the chain is skipped.

With score = 90, this lesson's chain prints A.

The first condition is score >= 90, and the >= operator includes equality, so 90 >= 90 is True. One branch runs and the chain ends there.

The near miss is instructive. Had the author written score > 90, a score of exactly 90 would have failed the first test and fallen through to the B branch, which is almost certainly not what a grading scheme intends. Off-by-one mistakes at boundaries are among the most common logic bugs, so the values sitting exactly on each threshold are the ones worth testing first.