Decisions with if, elif, and else
Unit ID: M04-U02 Estimated active time: 22-30 minutes
A branch runs conditionally
score = 8
if score >= 8:
print("Ready to continue")
The colon begins a block. Indentation marks the code controlled by the condition. Consistent indentation is part of Python syntax.
Choose one exclusive result
score = 6
if score >= 8:
result = "ready"
elif score >= 0:
result = "review"
else:
result = "invalid"
print(result)
Python checks branches from top to bottom and runs the first matching branch. The remaining branches are skipped.
Order from specific to fallback
This order is wrong:
if score >= 0:
result = "recorded"
elif score >= 8:
result = "ready"
A score of 9 matches the first branch, so the more specific second branch never runs.
Write the stronger threshold first:
if score >= 8:
result = "ready"
elif score >= 0:
result = "review"
else:
result = "invalid"
Independent if statements are different
Use separate if statements when more than one action may apply:
hours = 45
reasons = []
if type(hours) is not int:
reasons.append("hours must be an integer")
if type(hours) is int and not 0 <= hours <= 40:
reasons.append("hours must be from 0 to 40")
The second condition protects the numeric comparison from a wrong type.
Practice
Create a temperature_c classification:
- above 30:
hot; - from 20 through 30:
warm; - from 10 through 19:
cool; - below 10:
cold.
Test 31, 30, 20, 19, 10, and 9. Boundary tests reveal branch-order mistakes.
Takeaway
if runs a conditional block. elif and else create one exclusive path, while independent if statements allow several findings. Branch order is part of the logic. Next, we will repeat a step for every item in a collection.
