The elif condition is used when a program needs to choose between more than two possibilities. While if checks the first condition and else handles the final fallback, elif allows Python to test additional conditions in between.
In simple terms, elif means:
“If the previous condition was false, try this one.”
Python checks each condition from top to bottom. The moment it finds one that is true, it runs that block and ignores the rest.
Example:
1marks = 72
2
3if marks >= 90:
4 print("Grade A")
5elif marks >= 60:
6 print("Grade B")
7else:
8 print("Fail")Here, Python evaluates:
- If marks are 90 or more → Grade A
- Else if marks are 60 or more → Grade B
- Otherwise → Fail
Only one block is executed.
Nested elif in Python
A nested elif appears when elif is used inside a larger decision structure, often together with multiple if and else blocks. This allows Python to handle complex decision-making where many conditions must be checked in order.
Example:
1score = 85
2attendance = 75
3
4if score >= 90:
5 print("Top grade")
6elif score >= 60:
7 if attendance >= 75:
8 print("Pass with good standing")
9 else:
10 print("Pass but low attendance")
11else:
12 print("Fail")Here, Python applies two layers of logic:
- It first decides the grade based on
score. - If the score is in the middle range, it then checks
attendanceto decide the final result.
Why elif Is Important
Most real-world problems do not have only two outcomes. Grades, pricing, permissions, and system rules often depend on many ranges and conditions. elif keeps this logic clean and readable instead of forcing deeply nested if statements.
Conclusion
The elif statement allows Python to move through multiple possible conditions in a structured way. Nested elif and if blocks give Python the power to make detailed, real-world decisions, which is essential for building reliable and intelligent software.
