Elif
Conditional statements often require checking multiple possible conditions.
Python provides the elif (else if) keyword to handle such multi-way decision making efficiently.
Why elif Is Needed
Using multiple standalone if statements forces Python to evaluate every condition, even after finding the matching one. This wastes time and may execute unnecessary comparisons.
Example Without elif (Inefficient)
num = 2
if num == 1:
print("One")
if num == 2:
print("Two")
if num == 3:
print("Three")
if num == 4:
print("Four")
if num > 5:
print("Incorrect")Issue:
Even though num == 2, Python still checks all conditions unnecessarily.
The if-elif-else structure solves this by:
- Checking conditions in order
- Executing only the first matching block
- Skipping the rest automatically
This makes the program clean, efficient, and more readable.

The elif Syntax
if condition1:
statement1
elif condition2:
statement2
elif condition3:
statement3
else:
default_statementif→ used onceelif→ can be used multiple timeselse→ optional and used once as a fallback
Example With elif (Efficient & Correct)
num = 2
if num == 1:
print("One")
elif num == 2:
print("Two")
elif num == 3:
print("Three")
elif num == 4:
print("Four")
elif num == 5:
print("Five")
else:
print("Incorrect")Output:
TwoWhy only “Two”?
Because num == 2 is True, Python stops checking further conditions.
Handling Out-of-Range or Negative Input

If the value does not match any if or elif condition, the else block works as a safe fallback:
In the above example,
- Negative numbers → no explicit handling →
elsecovers them - Numbers > 5 → also handled by
else
This ensures complete coverage of all possible inputs.
Nested if With elif
elif can also contain another if-else block inside it, allowing multi-level decision-making.
num = 3
salary = 5
if num == 1:
print("One")
elif num == 2:
print("Two")
elif num == 3:
if salary >= 5:
print("Three")
else:
print("There")
elif num == 4:
print("Four")
elif num == 5:
print("Five")
else:
print("Incorrect")This structure helps implement complex business logic step-by-step.
Summary
elifallows checking multiple conditions in sequence, executing only the first condition that becomes True.- It improves efficiency by avoiding unnecessary checks, unlike multiple independent if statements.
elifcan be combined with nested if-else blocks to build multi-level decision logic.- The final else acts as a default fallback when no conditions match.
Written By: Muskan Garg
How is this guide?
Last updated on
