if, elif and else in Python
An if statement runs a block of code only when its condition is true. elif adds another condition to test when every condition before it fails, and else catches everything left over, so exactly one block in the chain runs.
Key facts
- In an
ifstatement, the condition line ends with a colon, and the block under it is indented, four spaces by convention. - In an
if/elif/elsechain, Python stops at the first condition that is true. elifis one word.else ifis a syntax error in Python.- Almost any value can be a condition.
False,None, zero and empty things count as false, and almost everything else as true.
How does an if statement work in Python?
Write if, a condition, and a colon, then indent the lines that should run when the condition is true. Python checks the condition once, runs the block or skips it, and continues with the first line after the block.
temperature = 5
if temperature < 10:
print("Wear a coat")
print("Have a good day")Wear a coat Have a good day
Change the temperature to 15 and run it again. The coat line disappears and the last line still prints, because it sits outside the block.
What is the difference between if, elif and else?
if starts the chain, elif adds another condition to try, and else runs when nothing before it was true. Python tests from the top and stops at the first match, so one block runs and the rest are skipped.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")B
The order matters. With 85, score >= 70 is also true, but Python never gets there because score >= 80 matched first. Put the strictest condition at the top.
Why use elif instead of a second if?
Because separate if statements are all tested, while an elif is tested only when the ones before it failed. Run the example, which tests the same score both ways, and count the lines.
score = 95
if score >= 90:
print("A")
if score >= 80:
print("B")
print("---")
if score >= 90:
print("A")
elif score >= 80:
print("B")A B --- A
Two ifs gave the student two grades. The chain gave one. Use elif when only one outcome should happen, and separate ifs when every true condition should run its own block.
Can I write if else on one line?
Yes, when the point is to choose a value. The form is value_if_true if condition else value_if_false, and Python calls it a conditional expression.
age = 20
status = "adult" if age >= 18 else "minor"
print(status)adult
Keep it for short choices. Once the two branches do more than produce a value, the four-line form is easier to read.
How do I nest if statements?
Indent an if inside another. Each level of indentation is one level of nesting, and each else belongs to the if at the same indentation.
logged_in = True
is_admin = False
if logged_in:
if is_admin:
print("Admin panel")
else:
print("Dashboard")
else:
print("Please log in")Dashboard
Two levels are fine. At three or more, combine the conditions with and, which the next lesson covers. Later in the course, functions give you another way out.
Can I use a string or list as a condition?
Yes. Python treats empty strings, empty collections, zero, False and None as false and almost everything else as true, so if name: is the usual way to check that a value is present.
name = ""
if name:
print(f"Hello, {name}")
else:
print("Hello, stranger")
items = [1, 2]
if items:
print(f"{len(items)} items")Hello, stranger 2 items
Common mistakes with if statements in Python
Each of these four mistakes with if statements gets an error message that names the exact line. Read it before you reread the code.
- IndentationError: expected an indented block after 'if' statement. The line under the
ifisn't indented. Add four spaces. - SyntaxError: expected ':'. The colon at the end of the condition is missing.
- Writing
else if. Python reports it as a missing colon afterelse. The keyword iselif. - A single
=in the condition. Python suggests==in the error message. Comparison uses two equals signs.
x = 3
if x > 2:
print("big") File "main.py", line 3
print("big")
^^^^^
IndentationError: expected an indented block after 'if' statement on line 2x = 1
if x == 2:
print("two")
else if x == 1:
print("one") File "main.py", line 4
else if x == 1:
^^
SyntaxError: expected ':'Exercise
The grade chain is in the wrong order, so a score of 85 prints D. Reorder the branches, moving each condition together with the print line under it, so the program prints B. Do not change the score or the letters.
score = 85
if score >= 60:
print("D")
elif score >= 70:
print("C")
elif score >= 80:
print("B")
else:
print("F")
B
Show the solution
score = 85
if score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
x = 10 if x > 5: print("big") elif x > 8: print("bigger") else: print("small")The first condition is true, so its block runs and the rest of the chain is skipped, even though x > 8 is also true.
-
2How do you write "else if" in Python?
Python spells it elif. The other forms are syntax errors.
-
3What does this program print?
name = "" print("yes" if name else "no")An empty string counts as false, so the conditional expression picks the else value.
-
4What does Python report when the line after an if is not indented?
The block under an if must be indented. Python names the if statement and its line number in the message.
-
5When should you use separate if statements instead of elif?
elif picks one branch. Independent ifs let every true condition run its block.