Python If, Elif and Else
What you will learn
- How
ifruns a block only when a condition is true - How
elseandelifadd other choices - Why indentation matters, and how to avoid the common errors
- How to nest conditions, and when to use
pass - That the order of an
elifchain decides the result
1. The if statement
An if statement runs some code only when a condition is true. The condition is any expression that gives a boolean (lesson 5.1):
temperature = 32
if temperature > 30:
print("It is hot")
print("Done")
It is hot
Done
Three rules for the first line:
- Start with the word
if. - Write the condition.
- End the line with a colon
:.
The lines that belong to the if are indented: moved to the right by the same amount, normally 4 spaces. That group of lines is called a block. The line print("Done") is not indented, so it runs always, whatever the condition says.
If temperature were 20, only Done would be printed.
Quick check: what makes a line part of the `if` block?
Being indented under the if line. There are no brackets or end words in Python: the indentation shows the structure.
2. else: the other choice
else runs when the condition is false. It has its own colon and its own block:
age = 15
if age >= 18:
print("Adult")
else:
print("Minor")
Minor
Exactly one of the two blocks runs, never both and never neither.
3. elif: more than two choices
elif (short for "else if") adds more conditions. Python checks them from top to bottom and runs the block of the first one that is true. The rest are skipped:
def grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
print([grade(s) for s in [95, 90, 89.9, 80, 75, 10]])
['A', 'A', 'B', 'B', 'C', 'F']
(def and return are covered in chapter 11: here grade just turns a score into a letter.) You can have as many elif parts as you like, and the final else is optional.
The order matters
Because the first true condition wins, put the most specific test first:
def bad_grade(score):
if score >= 50:
return "pass"
elif score >= 90:
return "distinction"
return "fail"
print(bad_grade(95))
pass
The score 95 is at least 50, so the first block runs and the distinction line can never be reached. Test score >= 90 first to fix it.
4. Nested conditions
A block can contain another if. The inner one is indented one more level:
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("enter")
else:
print("buy a ticket")
else:
print("too young")
enter
Deep nesting gets hard to read. Often you can flatten it with and and or (lesson 5.3).
5. Truthiness in conditions
The condition does not have to be a comparison. Any value works: empty or zero values count as false, and everything else as true (lesson 2.3):
name = ""
if name:
print("Hello,", name)
else:
print("No name given")
items = []
if not items:
print("The list is empty")
No name given
The list is empty
if name: is the usual Python way to ask "is it non-empty?", and if not items: asks "is it empty?".
6. pass: an empty block
A block cannot be empty. When you need a block that does nothing, for example while planning, write pass:
if True:
pass
print("after pass")
after pass
7. One-line forms
Short blocks can sit on the same line as the colon:
temp = 25
if temp > 30: msg = "hot"
elif temp > 20: msg = "warm"
else: msg = "cool"
print(msg)
warm
It works, but the normal layout is easier to read, and style guides prefer it. For choosing a value, lesson 5.4 shows a neater one-line form.
8. The errors you will meet
| Mistake | Error message |
|---|---|
no indentation after if ...: |
IndentationError: expected an indented block after 'if' statement on line 2 |
| lines indented by different amounts | IndentationError: unindent does not match any outer indentation level |
| missing colon | SyntaxError: expected ':' |
= instead of == |
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? |
| tabs mixed with spaces | TabError: inconsistent use of tabs and spaces in indentation |
else without an if |
SyntaxError: invalid syntax |
Read the line number in the message (lesson 1.3). Use 4 spaces for each level and let your editor insert them when you press Tab, so that tabs and spaces never mix.
Worked example: is it a leap year?
The rule: a year is a leap year if it is divisible by 4, except years divisible by 100, which are not, unless they are divisible by 400.
for y in [1900, 2000, 2024, 2100, 2023]:
if y % 400 == 0:
leap = True
elif y % 100 == 0:
leap = False
elif y % 4 == 0:
leap = True
else:
leap = False
print(y, leap)
1900 False
2000 True
2024 True
2100 False
2023 False
| Year | First true test | Result |
|---|---|---|
| 2000 | divisible by 400 | True |
| 1900 | divisible by 100 (not 400) | False |
| 2024 | divisible by 4 (not 100) | True |
| 2023 | none | False |
The order again matters: the exception to the exception (400) is tested first. (The for loop is covered in chapter 6.)
Common mistakes
- Forgetting the colon after
if,eliforelse. - Forgetting to indent the block, or indenting lines by different amounts.
- Mixing tabs and spaces. Use 4 spaces.
- Using
=instead of==. - Putting a broad condition before a narrow one in an
elifchain. - Writing
elsewith a condition.else:takes none; useelif.
Key takeaways
if condition:runs its indented block only when the condition is true.else:runs when it is false;elifadds further tests checked from top to bottom, and the first true one wins.- Indentation (normally 4 spaces) defines the block; the colon is required.
- Empty and zero values count as false in a condition;
passis an empty block. - Order tests from the most specific to the most general.
Practice
1. Write an if that prints Pass when marks is at least 40, and Fail otherwise.
Show answer
if marks >= 40:
print("Pass")
else:
print("Fail")
2. What does this print when n = 0: if n: print("yes") else: print("no")?
Show answer
no. The number 0 counts as false.
3. What is wrong with: if x > 3 (no colon) followed by an indented print?
Show answer
The colon is missing, so Python reports SyntaxError: expected ':'.
4. A shop gives 20% off for orders of 1000 or more and 10% off for orders of 500 or more. In what order should the two tests be written, and why?
Show answer
Test >= 1000 first. An order of 1200 is also at least 500, so testing 500 first would give it the smaller discount.
5. Write an if and elif that prints positive, negative or zero for a number n.
Show answer
if n > 0:
print("positive")
elif n < 0:
print("negative")
else:
print("zero")
6. What does pass do?
Show answer
Nothing. It is a placeholder for a block that must exist but has no instructions yet.