How do if/elif/else statements work in Python?
Python's conditional statement uses if, elif (else if), and else:
if condition1:
# runs if condition1 is truthy
elif condition2:
# runs if condition1 is falsy and condition2 is truthy
else:
# runs if all conditions are falsy
Key rules:
ifis required;elifandelseare optional- You can have any number of
elifblocks - Only the first matching branch executes (top-down)
- There is no
switchstatement in Python < 3.10 (usematchin 3.10+) - Python uses indentation (not braces) to define blocks
- The condition can be any expression; Python evaluates its truthiness
Truthiness: Falsy values are False, None, 0, 0.0, "", [], (), {}, set(). Everything else is truthy.
if condition:
action_a
elif other_condition:
action_b
else:
action_c
- Only one branch executes
- Top-down evaluation, first True wins
- else catches everything remaining
# Basic if/elif/else
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"Score: {score}, Grade: {grade}") # Score: 85, Grade: B
# Truthiness in conditions
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is empty") # This runs
# Multiple conditions with logical operators
age = 25
has_license = True
if age >= 18 and has_license:
print("Can drive")
elif age >= 18:
print("Old enough but no license")
else:
print("Too young")
# Nested if (sometimes better as elif)
x = 10
if x > 0:
if x > 100:
print("Large positive")
else:
print("Small positive") # This runs
else:
print("Non-positive")
# if without else
temperature = 100
if temperature > 95:
print("Warning: high temperature!") # This runs
# Checking multiple values
color = "red"
if color in ("red", "orange", "yellow"):
print("Warm color")
elif color in ("blue", "green", "purple"):
print("Cool color")
else:
print("Unknown color")
- •Only the first matching branch executes (top-down)
- •elif and else are optional
- •Any expression can be a condition (truthiness is evaluated)
- •Python uses indentation to define blocks, not braces
- •Use 'in' for checking membership instead of chained 'or'
- •if x = 5 is a SyntaxError -- use == for comparison, not =
- •if x == True is redundant and sometimes wrong -- just use if x
- •An empty if block requires pass as a placeholder
- •Order matters: if score >= 70 before score >= 80 would give wrong grade