Making Decisions · practice
Check Several Possibilities
An else statement chooses between two paths. Some decisions have more than two useful outcomes.
Python’s elif keyword lets one decision check several possibilities in order. The name is short for “else if.”
Add another condition with elif
Run this example:
Python checks the
temperature >= 30isFalse, so Python skips the first block.temperature >= 20isTrue, so Python assigns"Warm".The chain stops. Python does not continue to
else.
Only one branch in this chain runs.
The first true condition wins
An if/elif/else chain stops as soon as it finds a true condition. This makes the order of conditions part of the program’s logic.
Consider a score of 92:
The program prints Passed. The first condition is already true for every score of 60 or higher, so Python never reaches the more specific score >= 90 condition.
Put the narrower, higher boundary first:
Now the result is Excellent. A useful habit is to test a
Here is the same top-to-bottom rule with a score of 82: the 90 check says no, the 75 check says yes, and that first match skips every later branch.

You can use more than one elif
A chain can contain several elif branches:
Python checks only as far as necessary. With score = 74, the first two conditions are false and the third is true. The final else catches every score below 60.
The else branch is optional, but it is valuable when the program needs a result for every possible value.
One chain or separate decisions?
Use an if/elif/else chain when the branches are alternatives and exactly one should run.
Use separate if statements when each question is independent and more than one block may need to run. For example, a weather program might print both a heat warning and a wind warning. Those messages are not competing answers to one question.
Why must score >= 90 come before score >= 60 in this chain?
What does this code print?
age = 18
if age >= 21:
print("Level C")
elif age >= 18:
print("Level B")
elif age >= 16:
print("Level A")
else:
print("Not available")Classify a temperature
The exercise asks you to
Hotfor temperatures of30or more;Warmfor temperatures of at least20but less than30;Coolfor temperatures of at least10but less than20;Coldfor anything below10.
Use an if/elif/else chain with the boundaries in a clear order. The fixed temperature is 21, so the submitted program should choose Warm. After it passes, try 30, 20, 10, and 9 to check every boundary.
Task
Create an elif/else chain that assigns temperature_band.
Hotwhentemperatureis at least30Warmwhen it is at least20but did not match the earlier branchCoolwhen it is at least10but did not match an earlier branchColdotherwise
Keep temperature = 21 and the supplied print call unchanged.