Python
Topic 6 · Python basics · ⏱ about 3 h

Making Decisions: if, elif & else

Let your program choose what to do: comparisons, True and False, if, elif and else, combining tests with and, or and not, and the indentation that shows which lines belong to each choice.

Show:
In this topic
Beginner

Programs that decide

So far every line ran every time. Real programs make decisions: if the password is right, log in; otherwise, show an error. If the temperature is above 30, show a heat warning. In Python, decisions use if.

temperature = 34 if temperature > 30: print("Hot day: drink water") print("Have a nice day")

Read it as English: "if temperature is greater than 30, then print the warning". Three details matter:

  • The line ends with a colon :.
  • The lines that belong to the if are indented by 4 spaces. This group of lines is called a block. The editor indents for you after a colon.
  • The last line is not indented, so it runs every time, whatever the temperature.
Beginner

Comparisons give True or False

OperatorMeansExampleResult
==is equal to3 == 3True
!=is not equal to"a" != "b"True
< >less than, greater than2 > 5False
<= >=or equal5 >= 5True
inis inside"a" in "cat"True

The most common beginner mistake: = assigns a value, == compares. if age = 18: is a SyntaxError.

Python
age = 17
print(age >= 18)          # False
print(age == 17)          # True
print("Sita" == "sita")   # False: capitals matter
print(3 < age < 20)       # comparisons can be chained: True
Open in playground ↗
Beginner

if, elif, else: choosing one of several paths

else runs when the if test is False. elif ("else if") adds more tests. Python checks from the top and runs only the first block whose test is True, then skips the rest.

Python
score = 72

if score >= 85:
    grade = "High Distinction"
elif score >= 75:
    grade = "Distinction"
elif score >= 65:
    grade = "Credit"        # 72 lands here, and the remaining tests are skipped
elif score >= 50:
    grade = "Pass"
else:
    grade = "Fail"

print(score, "is a", grade)
Open in playground ↗
Try it

Watch a decision

Step through the code and see which test is checked, which block runs, and which are skipped.

Interactive: this part runs in your browser.

Beginner

Order matters

Because only the first True branch runs, put the most specific test first. This version is wrong: a score of 90 is also >= 50, so it gets "Pass" and the later tests never run.

if score >= 50: # 90 matches here first... grade = "Pass" elif score >= 85: # ...so this is never reached for 90 grade = "High Distinction"
Beginner

Combining tests: and, or, not

  • a and b is True only when both are True.
  • a or b is True when at least one is True.
  • not a flips True and False.
Python
age = 25
has_ticket = True
is_member = False

if age >= 18 and has_ticket:
    print("You can go in")

if is_member or age < 12:
    print("Free entry")
else:
    print("Please pay at the desk")

if not is_member:
    print("Ask about membership")

# Each side must be a complete test:
day = "Sunday"
print(day == "Saturday" or day == "Sunday")   # True
print(day in ("Saturday", "Sunday"))          # shorter, same result
Open in playground ↗
Beginner

Truthy and falsy values

An if does not need a comparison: any value can be tested. These count as False: 0, 0.0, an empty string "", empty collections [] {} and None. Everything else counts as True. So if name: means "if name is not empty".

name = input("Name: ").strip() if name: print("Hello", name) else: print("You did not type a name")
Beginner

Nested decisions and the short form

A block can contain another if; indent again. Keep nesting shallow, because deep nesting is hard to read; often and or elif is clearer. For a simple either/or value there is a one-line form: value_if_true if test else value_if_false.

Python
temp = 38.6
has_cough = True

if temp >= 37.5:
    if has_cough:
        print("Fever and cough: book a doctor")
    else:
        print("Fever: rest and drink fluids")
else:
    print("No fever")

label = "adult" if 20 >= 18 else "child"     # the short form
print(label)
Open in playground ↗
Beginner

Practice: check yourself

Write the code, then press ✔ Check my answer: hidden tests run your code and tell you exactly what is right. ▶ Run just shows the output. Stuck? Use a hint; the solution is there if you need it.

Exercise 1. Grade a score

Write the if/elif/else that sets grade from score: 85 or more → "HD", 75 or more → "D", 65 or more → "C", 50 or more → "P", otherwise "F". The checker will try several scores.

Exercise 2. Entry rules

Set can_enter to True when the person is 18 or older and has a ticket, or is a VIP (whatever their age or ticket). Use the variables age, has_ticket and is_vip.

Exercise 3. Leap years

A year is a leap year if it is divisible by 4, except years divisible by 100, which are only leap years if also divisible by 400. Set is_leap to True or False for year. (2024 yes, 2026 no, 1900 no, 2000 yes.)

Beginner

Summary

if runs a block when a test is True; elif adds more tests; else catches everything else. Only the first True branch runs. Tests are built from comparisons and combined with and, or and not, and blocks are marked by a colon and 4-space indentation.

Key words

condition
a test that is True or False
boolean
the type of True and False
comparison operator
== != < > <= >=
block
the indented lines that belong to an if, elif, else (or loop, or function)
indentation
spaces at the start of a line; 4 per level
logical operator
and, or, not
falsy
values that count as False: 0, "", [], {}, None

Common mistakes

  • = instead of == in a test.
  • Forgetting the colon at the end of if, elif or else lines.
  • Mixing indentation, or indenting by a different amount in the same block: IndentationError.
  • if day == "Sat" or "Sun": is always True, because "Sun" on its own is truthy. Write day == "Sat" or day == "Sun", or day in ("Sat", "Sun").
  • Putting a general test before a specific one, so the specific branch can never run.
  • Comparing input to a number: input() == 5 is always False, because input is text.
Check yourself

Quiz

1. Which operator checks whether two values are equal?

2. score = 90. Which branch runs?
if score >= 50: A / elif score >= 85: B / else: C

3. What is True and False?

4. What is not (5 > 3)?

5. Which value counts as False in an if?

6. Why is if colour == "red" or "blue": a bug?

Go deeper

📚 Further reading

Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.

Ready