elif / else
Updated March 15, 2026 · Keywords
keyword control-flow conditional if-statement
The elif and else keywords extend the basic if statement to handle multiple conditions in a single block. They let you create branching logic that responds differently based on varying conditions.
Syntax
if condition1:
# runs if condition1 is truthy
code_block
elif condition2:
# runs if condition1 is falsy but condition2 is truthy
code_block
elif condition3:
# runs if neither condition1 nor condition2 is truthy but condition3 is truthy
code_block
else:
# runs if all above conditions are falsy
code_block
How It Works
Python evaluates each condition in order:
- If the first
ifcondition is truthy, execute its block and skip allelifandelse - If falsy, check each
elifin order - Execute the first truthy
elifblock and skip the rest - If no conditions are truthy, execute the
elseblock (if present)
temperature = 75
if temperature > 85:
print("It is hot!")
elif temperature > 65:
print("It is pleasant")
elif temperature > 32:
print("It is chilly")
else:
print("It is cold!")
# Output: It is pleasant
else Without elif
The else keyword can stand alone after an if, providing a fallback when the condition is falsy:
is_raining = True
if is_raining:
print("Bring an umbrella")
else:
print("Enjoy the weather!")
# Output: Bring an umbrella
Multiple elif
You can chain as many elif statements as needed:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")
# Output: Grade: B
Common Use Cases
Range checking
age = 45
if age < 13:
category = "child"
elif age < 20:
category = "teenager"
elif age < 65:
category = "adult"
else:
category = "senior"
print(category)
# Output: adult
Input validation
def classify_input(value):
if value is None:
return "No value provided"
elif isinstance(value, str):
return "Text input"
elif isinstance(value, (int, float)):
return "Numeric input"
else:
return f"Unknown type: {type(value).__name__}"
print(classify_input("hello"))
# Output: Text input
print(classify_input(42))
# Output: Numeric input
State machines
def process_order(status):
if status == "pending":
return "Order is being reviewed"
elif status == "confirmed":
return "Order has been confirmed"
elif status == "shipped":
return "Order is on its way"
elif status == "delivered":
return "Order complete"
else:
return "Unknown status"
print(process_order("shipped"))
# Output: Order is on its way
Error handling flow
def handle_response(code):
if code == 200:
return "Success"
elif code == 401:
return "Unauthorized"
elif code == 404:
return "Not found"
elif code == 500:
return "Server error"
else:
return f"Unexpected code: {code}"
else with try/except
The else clause in a try/except block runs only if no exception was raised:
def divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return "Cannot divide by zero"
else:
return f"Result: {result}"
print(divide(10, 2))
# Output: Result: 5.0
print(divide(10, 0))
# Output: Cannot divide by zero
Performance Note
Since Python evaluates conditions sequentially, put the most likely conditions first for faster execution in typical cases:
# Good: most common case first
if user.is_active:
grant_access()
elif user.is_pending:
show_pending_message()
elif user.is_banned:
show_banned_message()
Avoid Redundant else
If all previous conditions cover every possible case, else is unnecessary:
# Redundant else - x is always either positive, negative, or zero
if x > 0:
print("positive")
elif x < 0:
print("negative")
else: # this is optional but harmless
print("zero")
# More concise without else
if x > 0:
print("positive")
elif x < 0:
print("negative")
else:
print("zero")
See Also
- bool built-in — how Python determines truthiness
- break keyword — exiting loops early
- continue keyword — skip to next iteration