The elif statement is used to check multiple conditions. It stands for “else if” and is executed when the previous if condition is False.
Syntax
if condition1:
# code
elif condition2:
# code
else:
# code
Basic Example
age = 18
if age < 18:
print("Minor")
elif age == 18:
print("Exactly 18")
else:
print("Adult")
Output:
Exactly 18
Multiple Elif Conditions
Example
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
elif marks >= 60:
print("Grade D")
else:
print("Fail")
Output:
Grade C
Elif with Strings
Example
color = "green"
if color == "red":
print("Stop")
elif color == "yellow":
print("Wait")
elif color == "green":
print("Go")
else:
print("Invalid Color")
Output:
Go
Elif with User Input
Example
number = int(input("Enter a number: "))
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
Output (Input: -5):
Negative
How Elif Works
Python checks conditions from top to bottom.
Example
score = 95
if score >= 90:
print("Excellent")
elif score >= 80:
print("Very Good")
elif score >= 70:
print("Good")
Output:
Excellent
Once a condition is True, the remaining elif conditions are skipped.
Summary
elifstands for “else if”.- It is used to check multiple conditions.
- Multiple
elifblocks can be used in a program. - Python executes only the first matching condition.
- Conditions are checked from top to bottom.
elifhelps avoid writing multiple separateifstatements.