Python If..Else
Programs need to make decisions: show a discount only to members, warn when the battery is low, reject a password that's too short. The if statement runs a block of code only when a condition is true.
The if statement
battery = 15
if battery < 20:
print("Battery low - please charge.")
print("Status check finished.")Battery low - please charge.
Status check finished.
The condition is followed by a colon, and the body is indented. Any expression can be a condition — Python uses its truthiness (see the Booleans lesson).
else
else provides the alternative that runs when the condition is false:
age = 16
if age >= 18:
print("You can vote.")
else:
print(f"You can vote in {18 - age} years.")You can vote in 2 years.
elif
To test several conditions in turn, use elif (short for "else if"). Python checks them top to bottom and runs only the first block whose condition is true:
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 65:
return "C"
else:
return "F"
for s in [95, 83, 80, 70, 42]:
print(s, grade(s))95 A
83 B
80 B
70 C
42 F
Because the checks are ordered, score >= 80 doesn't need to also say score < 90 — a score of 90 or more never reaches that line.
Combining conditions
Use and, or and not, plus chained comparisons:
temperature = 26
raining = False
if 20 <= temperature <= 30 and not raining:
print("Perfect day for a walk.")
day = "Sun"
if day == "Sat" or day == "Sun":
print("Weekend!")
if day in ("Sat", "Sun"): # shorter and clearer
print("Still the weekend!")Perfect day for a walk.
Weekend!
Still the weekend!
Nested if
An if can sit inside another if. Keep nesting shallow — two levels is usually the most that stays readable:
logged_in = True
is_admin = False
if logged_in:
if is_admin:
print("Welcome to the admin panel.")
else:
print("Welcome back!")
else:
print("Please log in.")Welcome back!
The conditional expression
For simple either/or values, Python has a one-line conditional expression (often called the ternary operator):
n = 7
parity = "even" if n % 2 == 0 else "odd"
print(n, "is", parity)
items = 1
print(f"{items} file{'s' if items != 1 else ''} copied")7 is odd
1 file copied
pass — an empty block
A block can't be empty. While sketching code, put pass as a placeholder that does nothing:
if user_is_banned:
pass # TODO: decide what to do hereQuick reference
| Form | Use for |
|---|---|
if cond: |
do something only when cond is true |
if … else … |
choose between two paths |
if … elif … elif … else … |
choose one of many paths |
a if cond else b |
pick one of two values inline |
Tip: Compare to
True,FalseorNonesparingly: writeif done:rather thanif done == True:, andif result is None:rather thanif result == None:.
Test yourself
With x = 85, which branch runs in if x > 50: ... elif x > 80: ... else: ...?
- the
ifbranch - the
elifbranch - the
elsebranch - both
ifandelif
What does "big" if 3 > 5 else "small" evaluate to?
- "big"
- "small"
- True
- False
Which statement can be used as a do-nothing placeholder in an empty block?
- skip
- continue
- pass
- none