The Elif Keyword
With elif, Python says: "the conditions so far were not true, so try this one next".
This lets you test several expressions in turn. The block belonging to the first expression that evaluates to True is the one that runs.
Example
if and elif to compare two equal variables and print a message when they are equal.
Output: complete Python program
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Multiple Elif Statements
There is no limit on how many elif statements you can write. Python goes through them in order and runs the block of the first condition that turns out true.
Example
elif statements to determine and print the letter grade.
Output: complete Python program
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
How Elif Works
Python works through an elif chain from top to bottom. The moment one condition is true, its block runs and the rest of the chain is skipped.
Important: More than one condition may be true, but only the block of the earliest one runs. Python never goes on to the others.
Example
if and elif.
Output: complete Python program
age = 25
if age < 13:
print("You are a child")
elif age < 20:
print("You are a teenager")
elif age < 65:
print("You are an adult")
elif age >= 65:
print("You are a senior")
When to Use Elif
Reach for elif when your conditions rule each other out. A chain like this is more efficient than a row of separate if statements, since the checking ends as soon as one condition is true.
Example
if and elif.
Output: complete Python program
day = 3
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")
elif day == 7:
print("Sunday")