14.1 Conditionals
Make explicit decisions using if, elif, and else.
Before you start
Work through the earlier fundamentals chapters. Use a Python 3 interpreter and run each example locally.
Core concepts
An if branch runs when its condition is truthy. elif is checked only when earlier branches failed, and else covers the remaining cases. Indentation defines the body.
Empty collections, zero, None, and empty strings are falsy. Use is None when you specifically mean a missing value; a value of zero may still be valid. Compare values with ==, not is.
Worked example
cpu = 85
if cpu >= 90:
print("critical")
elif cpu >= 70:
print("warning")
else:
print("healthy")
Mini lab
Classify usage values 0, 70, 90, and 100. Expected labels: healthy, warning, critical, critical. Reject values outside 0–100.
Hint
Start with the smallest input. Print intermediate values while exploring, then replace those prints with checks of the expected result.Show a solution
for cpu in [0, 70, 90, 100]:
if not 0 <= cpu <= 100:
raise ValueError("CPU must be between 0 and 100")
if cpu >= 90:
print("critical")
elif cpu >= 70:
print("warning")
else:
print("healthy")
Knowledge check
Why should the >= 90 branch come before >= 70?
Check your answer
A value of 95 also satisfies >= 70. The first matching branch wins.Common mistake
Test values exactly on either side of a threshold. Avoid conditions that accidentally exclude zero.
Completion checklist
- Run the example and explain its output.
- Complete the mini lab without copying the solution.
- Test an edge case and explain how the code handles it.
- Answer the knowledge check in your own words.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form