Creating Multiple Branches with elif
So far, we've looked at two-way decisions using if
and else
. But sometimes, we want to check more than two conditions — this is where elif
(short for else if) comes in.
The elif
Statement
elif
lets you check multiple conditions, one after another. If the first if
is false, Python checks the elif
. If none match, it finally runs the else
(if there is one).
Syntax:
if condition1:
# runs if condition1 is true
elif condition2:
# runs if condition2 is true
elif condition3:
# runs if condition3 is true
else:
# runs if none are true
Python checks the conditions from top to bottom, and stops at the first one that is true.
Example:
score = 85
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")
Output
Grade: B
Why Use elif
?
Without elif, you'd have to nest if
statements, which makes code harder to read.
Compare this:
if score >= 90:
print("Grade: A")
else:
if score >= 80:
print("Grade: B")
else:
if score >= 70:
print("Grade: C")
To this:
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
Much cleaner, right?
Real-world Example
day = "Monday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
elif day == "Friday":
print("Almost weekend!")
else:
print("It's a weekday.")
elif
Chains Can Be as Long as Neede
You can use as many elif
statements as you want — Python will evaluate them in order until it finds a match.
Exercise: Try It Yourself!
Write a program that asks the user for a number between 1 and 12 and prints the corresponding month name. If the number is not in the range, print "Invalid month number".
Sample output
Enter month number: 4
April
Hint:
Use int(input(...))
to convert user input into a number.