Kodewick
Lesson 8 of 31Contents

if, elif and else

Lesson 8 of 31 · Part 1 · Basics · about 20 minutes

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.

main.py
1oil = 22if oil < 3:3    print("Oil is low.")4    print("Wick heads to the shop.")5print("Done checking.")
Output
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.

main.py
1oil = 22if oil < 3:3print("Oil is low.")
Output
  File "main.py", line 3
    print("Oil is low.")
IndentationError: expected an indented block after 'if' statement on line 2

An 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.

main.py
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).")
Output
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.

main.py
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.")
Output
About half full.
Guess first

What does this print?

1score = 952if score >= 50:3    print("Pass")4elif score >= 90:5    print("Excellent")6else:7    print("Try again")

Combining conditions

A condition can be any expression that gives True or False, including and, or, not, chained comparisons and in.

main.py
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.")
Output
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".

main.py
1name = ""2if name:3    print(f"Hello, {name}!")4else:5    print("You didn't type a name.")
Output
You didn't type a name.

This pairs well with input(). Now you can finally act on .isdigit() before converting:

main.py
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.")
Output
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.

main.py
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.")
Output
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.

main.py
1lamps = 12word = "lamp" if lamps == 1 else "lamps"3print(lamps, word)4print("Night" if lamps > 0 else "Day")
Output
1 lamp
Night

Use it for short choices like this. For anything that does more, write a normal if.

Common mistakes

MistakeExampleWhat happens
Missing colonif x > 3SyntaxError
= instead of ==if x = 3:SyntaxError
Body not indentedif x > 3: then print(x) at the left edgeIndentationError
or with a bare valueif 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:

main.py
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.")
Output
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.

Exercise 1

Even or odd

Print even if n divides by 2 with nothing left over, otherwise odd.

It should print
odd
exercise1.py
1n = 72# Your code here
Output
Press Run or Ctrl+Enter
Exercise 2

Lamp brightness

Print dim below 30, normal from 30 up to 69, and bright from 70 up.

It should print
bright
exercise2.py
1level = 702if level < 30:3    print("dim")
Output
Press Run or Ctrl+Enter
Exercise 3

Fix the check

This program should print Please answer yes or no. for the answer below, but it says Got it. Fix the condition.

It should print
Please answer yes or no.
exercise3.py
1answer = "maybe"2if answer == "yes" or "no":3    print("Got it.")4else:5    print("Please answer yes or no.")
Output
Press Run or Ctrl+Enter

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.
  • else runs when the condition is false; elif adds more cases, and only the first true branch runs.
  • Conditions can use and, or, not, in and truthy values like if name:.
  • A if condition else B picks one of two values on one line.
  • Watch for a missing colon, = instead of ==, and x == "a" or "b".