TExcelTAD
Home › Python › Python If..Else

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

python · try it yourself
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:

python · try it yourself
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:

python · try it yourself
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:

python · try it yourself
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:

python · try it yourself
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):

python · try it yourself
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:

python
if user_is_banned:
    pass   # TODO: decide what to do here

Quick 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, False or None sparingly: write if done: rather than if done == True:, and if result is None: rather than if result == None:.

Test yourself

With x = 85, which branch runs in if x > 50: ... elif x > 80: ... else: ...?

  1. the if branch
  2. the elif branch
  3. the else branch
  4. both if and elif

What does "big" if 3 > 5 else "small" evaluate to?

  1. "big"
  2. "small"
  3. True
  4. False

Which statement can be used as a do-nothing placeholder in an empty block?

  1. skip
  2. continue
  3. pass
  4. none