Lesson 12 of 4030%
(Progress persistence is disabled until Phase 9)
Python
Beginner
if, elif and else
Handle multiple conditions and fallback scenarios.
if, elif, and else
What You’ll Learn
You’ll learn how to handle multiple conditions using elif (else if) and provide a fallback using else.
The else Statement
The else keyword catches anything which isn’t caught by the preceding conditions.
age = 15
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The elif Statement
The elif keyword is Python’s way of saying “if the previous conditions were not true, then try this condition”.
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
Expected Output:
Grade: B
Order Matters!
Python checks conditions from top to bottom. As soon as it finds a True condition, it executes that block and skips the rest of the if/elif/else chain.
If we put score >= 70 at the top, an 85 would incorrectly get a ‘C’!