Elif Statement in python
Introduction
The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition".
The elif keyword allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.
Syntax
if condition1:
# code block 1
elif condition2:
# code block 2
Key Points
-
means else if.elif - Used to test multiple conditions.
-
Can have multiple
blocks.elif - Python checks conditions from top to bottom.
-
Once a condition is
, the remaining conditions are skipped.True
Example 1: Grade Calculator
marks = 85
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
Output
Grade B
Explanation
The first condition is , but False is marks >= 75, so Python prints Grade B.
True
Example 2: Traffic Light System
signal = "yellow"
if signal == "red":
print("Stop")
elif signal == "yellow":
print("Get Ready")
elif signal == "green":
print("Go")
Output
Get Ready
Explanation
Since the signal is , the corresponding "yellow" block executes.
elif
Example 3: Age Category
age = 20
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 60:
print("Adult")
Output
Adult
Explanation
The age is 20, so the third condition (age < 60) becomes True.
Common Mistakes
❌ Wrong:
elif age > 18:
print("Adult")
( cannot be used without a preceding elif.)
if
✅ Correct:
if age < 18:
print("Minor")
elif age >= 18:
print("Adult")
The statement helps handle multiple conditions efficiently. It makes code more readable and avoids writing multiple separate elif statements.
if