if, elif and else
Until now every line of a program ran, every time. if lets a program run some lines only when a condition is true, so it can react: light the lamps only after dark, refill only when the oil is low.
The if statement
An if has three parts: the word if, a condition that is true or false (lesson 7), and a colon. The indented lines below it are its body. They run only when the condition is true; then the program carries on below.
1oil = 22if oil < 3:3 print("Oil is low.")4 print("Wick heads to the shop.")5print("Done checking.")
Oil is low. Wick heads to the shop. Done checking.
Change oil to 5 and run it again: the two indented lines are skipped, but Done checking. still appears, because it is not indented.
Indentation matters
Python uses indentation, the spaces at the start of a line, to see which lines belong to the if. Other languages use curly braces { } for this; Python uses only the spaces. The usual size is 4 spaces, and every line in one body must line up.
1oil = 22if oil < 3:3print("Oil is low.")
File "main.py", line 3
print("Oil is low.")
IndentationError: expected an indented block after 'if' statement on line 2An IndentationError means Python expected an indented body after the colon and found none. Lines that start a little too far in or out cause the same kind of error.
Tip: In the editor, pressing Tab puts in 4 spaces. If you type the spaces yourself, keep every line of a body at the same depth.
else: the other case
else gives the program something to do when the condition is false. Exactly one of the two bodies runs, never both.
1age = int(input("How old are you? "))2if age >= 18:3 print("You can rent a house in town.")4else:5 print(f"Come back in {18 - age} year(s).")
How old are you? 17 Come back in 1 year(s).
else has no condition of its own, and it lines up with its if.
elif: more than two choices
For several cases, add elif (short for *else if*) branches. Python tests the conditions from the top down and runs the first one that is true. The rest are skipped, even if they would also be true.
1oil = 62if oil == 0:3 print("Empty! Refill now.")4elif oil < 5:5 print("Running low.")6elif oil < 10:7 print("About half full.")8else:9 print("Full.")
About half full.
What does this print?
1score = 952if score >= 50:3 print("Pass")4elif score >= 90:5 print("Excellent")6else:7 print("Try again")
95 >= 50 is true, so the first body runs and Python skips every branch after it. To get Excellent, test the stricter condition first: put score >= 90 at the top.
Combining conditions
A condition can be any expression that gives True or False, including and, or, not, chained comparisons and in.
1hour = 222is_raining = False3if hour >= 18 and not is_raining:4 print("A good night for a walk.")5if 6 <= hour < 18:6 print("Daytime")7if "a" in "lamp":8 print("Found an a.")
A good night for a walk. Found an a.
These are three separate ifs, so each one is checked on its own. That is different from elif, where only one branch can run.
Truthy values in if
Lesson 7 showed that empty strings and zero count as false. An if uses that, so you can test a value directly: if name: means "if name is not empty".
1name = ""2if name:3 print(f"Hello, {name}!")4else:5 print("You didn't type a name.")
You didn't type a name.
This pairs well with input(). Now you can finally act on .isdigit() before converting:
1text = input("How many lamps? ").strip()2if text.isdigit():3 print("Lamps to light:", int(text))4else:5 print(f"'{text}' is not a whole number.")
How many lamps? seven 'seven' is not a whole number.
Nested if
A body can contain another if. Each level is indented 4 more spaces.
1is_dark = True2oil = 13if is_dark:4 if oil > 0:5 print("Lighting the lamp.")6 else:7 print("No oil left.")8else:9 print("Wait for nightfall.")
Lighting the lamp.
Two levels are fine. When it goes deeper, and or elif usually reads better: if is_dark and oil > 0:.
One-line choices
When you only need to pick one of two values, a conditional expression fits on one line: A if condition else B gives A when the condition is true, otherwise B.
1lamps = 12word = "lamp" if lamps == 1 else "lamps"3print(lamps, word)4print("Night" if lamps > 0 else "Day")
1 lamp Night
Use it for short choices like this. For anything that does more, write a normal if.
Common mistakes
| Mistake | Example | What happens |
|---|---|---|
| Missing colon | if x > 3 | SyntaxError |
= instead of == | if x = 3: | SyntaxError |
| Body not indented | if x > 3: then print(x) at the left edge | IndentationError |
or with a bare value | if x == "a" or "b": | always true |
The last one is sneaky because no error appears. Python reads it as (x == "a") or ("b"), and "b" is a non-empty string, so it always counts as true:
1answer = "no"2if answer == "yes" or "y":3 print("Lighting the lamps!")4if answer == "yes" or answer == "y":5 print("This line only runs for yes or y.")
Lighting the lamps!
Write the full comparison on both sides of or.
Practice
Write the code, then press Check. A hint costs nothing; the answer is there when you need it.
Even or odd
✓Print even if n divides by 2 with nothing left over, otherwise odd.
odd
1n = 72# Your code here
Lamp brightness
✓Print dim below 30, normal from 30 up to 69, and bright from 70 up.
bright
1level = 702if level < 30:3 print("dim")
Fix the check
✓This program should print Please answer yes or no. for the answer below, but it says Got it. Fix the condition.
Please answer yes or no.
1answer = "maybe"2if answer == "yes" or "no":3 print("Got it.")4else:5 print("Please answer yes or no.")
What you learned
if condition:runs its indented body only when the condition is true.- Indentation (4 spaces) shows which lines belong to the
if; wrong indentation is an error. elseruns when the condition is false;elifadds more cases, and only the first true branch runs.- Conditions can use
and,or,not,inand truthy values likeif name:. A if condition else Bpicks one of two values on one line.- Watch for a missing colon,
=instead of==, andx == "a" or "b".