Chaining if-elif-else

Concepts covered: Conditionals

Many decisions have more than 2 outcomes: a grade band, a shipping tier, a greeting that depends on the time of day. elif, short for else-if, adds another condition to the chain. Python tests the conditions from top to bottom, runs the block of the first one that is True, and skips every condition after it without evaluating them. The final else runs only when every condition before it was False.

score = 83

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(grade)

With score = 83, Python tests 83 >= 90 first. It comes out False, so Python moves to the next condition. 83 >= 80 is True, so grade becomes "B" and the chain is finished. The condition 83 >= 70 is also True, but it is never evaluated, because the chain stopped at the first match. One block in a chain runs, however many of its conditions would have passed.

Tracing a chain step by step

The animation prices a ride by distance. Watch which conditions are evaluated for a 12 km trip: the first is tested and fails, the second is tested and passes, and the highlight never reaches the third or the else.

distance_km = 12

if distance_km <= 5:
    fare = 4
elif distance_km <= 15:
    fare = 9
elif distance_km <= 30:
    fare = 15
else:
    fare = 25

print("Fare:", fare)
Fare: 9
distance_kmConditions testedFirst True conditionfare
31`distance_km <= 5`4
122`distance_km <= 15`9
303`distance_km <= 30`15
453none, so else runs25

Order decides the answer

Because the first True condition wins, the order of the conditions is part of the logic. The program below has the same 3 bands as the grade example, written from lowest threshold to highest. Predict what a score of 95 prints.

score = 95

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

Output:

C

A score of 95 is at least 70, so the first condition is True and Python prints C. The conditions that would have produced A or B are never reached. When conditions overlap, put the most specific one first. In a chain of >= tests that is the highest threshold, and in a chain of <= tests it is the lowest.

A chain against separate if statements

A set of 3 separate if statements looks similar on the page but behaves differently. Each one is tested independently, so every condition that is True runs its block. The program below runs the same 3 conditions both ways against a score of 95.

score = 95

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

if score >= 90:
    print("separate: A")
if score >= 80:
    print("separate: B")
if score >= 70:
    print("separate: C")

Output:

chain: A
separate: A
separate: B
separate: C

The chain prints 1 line, because it stops at the first match. The separate statements print 3, because 95 satisfies all 3 conditions and nothing stops the later ones from running. When the outcomes are meant to exclude each other, a chain is the right tool. When several outcomes can apply at once, separate if statements are.

Rules of an if-elif-else chain

What does this program print?

stock = 0

if stock > 10:
    print("In stock")
elif stock > 0:
    print("Low stock")
elif stock == 0:
    print("Sold out")
else:
    print("Negative stock")

Turning a rule stated in words into a chain takes 3 decisions: which comparison each band needs, which band is tested first, and which keyword opens each later band. With < tests the lowest threshold comes first, each later band starts with elif, and the last band, which has no upper limit, becomes the else.

About this lesson

This section is part of the Control Flow: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.