Python If...Else
Python if else statements let your program make decisions. The if statement runs a block of code only when a condition is True, elif checks further conditions, and else handles everything that is left. Remember the colon at the end of each line and the indented block below it.
The if Statement
balance = 500
price = 350
if price <= balance:
print("Purchase approved")
balance -= price
print("Balance:", balance)Purchase approved Balance: 150
if, elif and else
Python checks each condition from top to bottom and runs only the first block whose condition is True. If none match, the else block runs.
def grade(score):
if score >= 90:
return "A"
elif score >= 75:
return "B"
elif score >= 50:
return "C"
else:
return "F"
for s in [95, 80, 62, 30]:
print(s, grade(s))95 A 80 B 62 C 30 F
Combining Conditions
Use and, or and not to combine conditions, and nest if statements when a second check only makes sense after the first.
age = 22
has_id = True
country = "UK"
if age >= 18 and has_id:
if country in ("UK", "Spain"):
print("Welcome to the event")
else:
print("Welcome")
else:
print("Entry denied")Welcome to the event
One-Line If Else (Conditional Expression)
For simple choices between two values, Python has a compact form: value_if_true if condition else value_if_false.
stock = 0
status = "in stock" if stock > 0 else "sold out"
print(status)
n = 7
print("even" if n % 2 == 0 else "odd")sold out odd
The pass Statement
A block cannot be empty. If you want to write the structure now and fill it later, use pass as a placeholder that does nothing.
if user_is_admin:
pass # TODO: show admin toolsPython match case
Python 3.10 added match statements, which compare a value against several patterns. The underscore _ acts as the default case. For simple value checks they read more cleanly than a long elif chain.
def http_status(code):
match code:
case 200:
return "OK"
case 404:
return "Not Found"
case 500 | 502 | 503:
return "Server Error"
case _:
return "Unknown"
print(http_status(404))
print(http_status(502))
print(http_status(301))Not Found Server Error Unknown
Frequently asked questions
What is elif in Python?
elif is short for "else if". It checks another condition only when all the conditions above it were False. You can have as many elif blocks as you need.
How do I write if else on one line in Python?
Use a conditional expression: result = "yes" if condition else "no". Keep it for short, simple choices.
Does Python have a switch statement?
Python 3.10 and newer have match...case, which covers switch-style logic and much more. Older versions use if/elif chains or a dictionary lookup.