if, elif, else
An if statement runs code only when a condition is True. Add else and elif to choose between two or more actions.
Read Comparisons and Logical Operators first.
One condition: if
battery = 15if battery <= 20: print("Charge your phone")print("Battery check complete")battery <= 20 is True, so both lines print. Change battery to 80 and
only Battery check complete prints.
- The
ifline ends with a colon (:). - The code inside the
ifis indented by four spaces. It runs only when the condition isTrue. - The last
printis back at the left edge, so it always runs.
Two choices: if / else
else runs when the if condition is False.
battery = 80if battery <= 20: print("Charge your phone")else: print("You have enough charge")80 <= 20 is False, so Python skips the first branch and prints
You have enough charge. Exactly one of the two messages prints.
else: lines up with if. It has a colon but no condition.
Three choices: if / elif / else
elif means "else if". Python checks it only when the conditions above it
were False.
battery = 35if battery <= 20: print("Low battery")elif battery <= 50: print("Half full or less")else: print("Plenty of charge")35 <= 20 is False. 35 <= 50 is True, so Python prints
Half full or less and skips the rest. Only the first matching branch runs.
Why the order matters
A battery of 15 matches both battery <= 20 and battery <= 50. Put the
wider check first and the low-battery branch is never reached:
battery = 15if battery <= 50: print("Half full or less")elif battery <= 20: print("Low battery")This prints Half full or less, not Low battery. Check the narrowest
condition first.
Note: Two separate if statements are two separate decisions. Both can
run. Use elif when only one branch should run.
See also: Comparisons and Logical Operators, Nested Loops & Ifs.
Your turn
Add an elif branch so a battery of 50 or less prints Time to charge soon.
Time to charge soon
battery = 35if battery <= 20: print("Low battery")# add an elif here: 50 or less prints Time to charge soonelse: print("Plenty of charge")Advanced reading
- The ternary operator — pick one of two values in a single line with
x if condition else y. - match and case — compare one value against many fixed options.