Theory
Cascading Conditional Statements in Python
Sometimes you need to check several different conditions in sequence and execute only one matching branch.
Python allows this with the if ... elif ... else structure—often called cascading conditionals.
Example: determining the quadrant
We can rewrite the nested quadrant example using a cascade:
x = int(input())
y = int(input())
if x > 0 and y > 0:
print("First quadrant")
elif x > 0 and y < 0:
print("Fourth quadrant")
elif y > 0:
print("Second quadrant")
else:
print("Third quadrant")
How it works
- Conditions are checked from top to bottom.
- The first true condition’s block runs, and the rest are skipped.
- If none are true, the
elseblock runs (if present). - You can have as many
elifbranches as needed, but only oneifand at most oneelse.
When to use cascades instead of nesting
- When all conditions are mutually exclusive—only one can be true.
- To improve readability compared to deep nested
ifs. - When checking multiple possibilities of the same variable(s).
Example: grading system
score = int(input("Enter score: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Only one of these branches will execute, even if multiple conditions could be true.
Tips for using if/elif/else
- Order matters: put more specific conditions before more general ones.
- If two conditions can be true at the same time but you want both to execute, use separate
ifstatements instead ofelif. - Keep conditions simple for readability; break complex checks into variables.
Quick practice
- Classify a temperature as
cold(< 0),cool(0–15),warm(16–25), orhot(> 25). - Given an integer 1–7, print the corresponding weekday name.
- Given a test score 0–100, assign a letter grade using an
if/elif/elsecascade.
Show sample solutions
# 1) Temperature classification
t = int(input())
if t < 0:
print("cold")
elif t <= 15:
print("cool")
elif t <= 25:
print("warm")
else:
print("hot")
2) Weekday
day = int(input())
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
else:
print("Sunday")
3) Grade
score = int(input())
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")