if / elif / else
Run different code depending on a condition.
Syntax
if condition:
...
elif other:
...
else:
...The if statement runs a block only when a condition is True. Add elif (else if) for more choices, and else for a fallback.
Structure
Each condition ends in a colon :, and the code to run is indented below it. Python checks each condition in order and runs the first that is True.
Example
hour = 14
if hour < 12:
print('Good morning')
elif hour < 18:
print('Good afternoon')
else:
print('Good evening')
# Output:
# Good afternoonWhen to use it
- A ticket booking app checks age with if/elif/else to apply child, adult, or senior pricing.
- An authentication flow shows different pages based on whether a user is logged in.
- A temperature monitor alerts operators with different severity messages depending on the reading.
More examples
Simple if/else
Runs the if branch because the condition is True, skipping the else block.
balance = 250
if balance >= 100:
print('Sufficient funds')
else:
print('Insufficient funds')
# Output:
# Sufficient fundsif / elif / else chain
Uses elif to check multiple ranges in order and assigns the correct letter grade.
score = 72
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print(grade) # CNested if for combined conditions
Nests an inner if inside an outer if to apply a tiered discount based on membership and spend.
is_member = True
cart_total = 120
if is_member:
if cart_total >= 100:
discount = 0.15
else:
discount = 0.05
else:
discount = 0
print(f'Discount: {discount * 100:.0f}%') # Discount: 15%
Discussion