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.
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.
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
ifare 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.
Comparisons give True or False
| Operator | Means | Example | Result |
|---|---|---|---|
== | is equal to | 3 == 3 | True |
!= | is not equal to | "a" != "b" | True |
< > | less than, greater than | 2 > 5 | False |
<= >= | or equal | 5 >= 5 | True |
in | is inside | "a" in "cat" | True |
The most common beginner mistake: = assigns a value, == compares. if age = 18: is a SyntaxError.
age = 17
print(age >= 18) # False
print(age == 17) # True
print("Sita" == "sita") # False: capitals matter
print(3 < age < 20) # comparisons can be chained: Trueif, 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.
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)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.
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.
Combining tests: and, or, not
a and bis True only when both are True.a or bis True when at least one is True.not aflips True and False.
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 resultTruthy 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".
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.
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)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.
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.
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.
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.)
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,eliforelselines. - 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. Writeday == "Sat" or day == "Sun", orday in ("Sat", "Sun").- Putting a general test before a specific one, so the specific branch can never run.
- Comparing input to a number:
input() == 5is always False, because input is text.
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?
📚 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.
- The Python Tutorial: More Control Flow Tools ↗ if, for, range, functions, arguments and lambdas, from python.org
- Automate the Boring Stuff with Python (Al Sweigart) ↗ free online book: practical Python for beginners