Loading...
Loading...
Handle multiple conditions with elif
Sometimes you need to check more than two possibilities. elif (short for "else if") lets you chain multiple conditions together. Python checks each condition in order, and runs the first one that's True.
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")For score = 85, Python goes step by step:
Any time you have multiple categories based on a value:
| ❌ Wrong | Why | ✅ Right |
|---|---|---|
| `if ... elif ... if ...` instead of `elif` | Using `if` again creates a NEW separate check | Use `elif` for chained conditions |
| Checking `>= 60` before `>= 90` | The 90+ students match `>= 60` first! | Order from highest to lowest |
| `elif (score >= 80):` | Works but extra parens are unnecessary | `elif score >= 80:` |
Write a program that takes a temperature (in Celsius) and prints:
Use if/elif/else structure with order from most extreme to least.
temp = 20
if temp <= 0:
print("Freezing")
elif temp <= 15:
print("Cold")
elif temp <= 25:
print("Warm")
else:
print("Hot")