Skip to content

if, elif, and else

~15 min ยท prerequisite: Booleans and comparisons

What you will be able to do

  • Write an if statement that runs a block of code only when a condition is True.
  • Add else for the case where the condition is False, and elif for further cases.
  • Explain how indentation decides which lines belong to a block, and fix the error when it is wrong.

The idea

An if statement starts with the word if, then a condition, then a colon. The lines below it, indented, form a block. The usual style is four spaces for each level of indentation.

When Python reaches an if statement, it checks the condition. If the condition is True, it runs the block. If the condition is False, it skips the block and continues with the first line that is not indented under the if.

An else block follows an if block and runs when the condition is False. An elif block, short for "else if", adds another condition. Python checks an elif condition only when every condition above it was False.

Python checks the conditions from top to bottom and runs the first block whose condition is True. At most one block in a chain runs. If no condition is True and there is no else, nothing runs.

Think of a row of road signs. Python takes the first road whose sign is true, and never reads the rest.

Worked example

temperature = 30

if temperature > 25:
    print("Hot")
elif temperature > 15:
    print("Mild")
else:
    print("Cold")

Line by line, this is what Python does:

  1. temperature = 30 stores the integer 30.
  2. if temperature > 25: checks the first condition. 30 is greater than 25, so the condition is True.
  3. print("Hot") is indented under the if, so it is part of that block. It runs and shows Hot.
  4. Python does not check the elif condition, because the if condition was already True.
  5. The else block is skipped for the same reason.

The output is Hot. If you change temperature to 20, the if condition is False, the elif condition is True, and the output is Mild.

Try it

Each block stores its result in a variable and checks it with assert.

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
assert grade == "B"
age = 12
if age >= 18:
    ticket = "adult"
else:
    ticket = "child"
assert ticket == "child"
number = 150
if number > 100:
    label = "big"
elif number > 10:
    label = "medium"
else:
    label = "small"
assert label == "big"

number = 50
if number > 10:
    label = "medium"
elif number > 100:
    label = "never checked"
assert label == "medium"

label = "unchanged"
if 1 > 2:
    label = "changed"
assert label == "unchanged"

The second part of the last block shows the order of the chain. The value 50 is greater than 10, so the first elif runs and the second one is never checked. The third part shows that an if with no matching condition and no else leaves the variable alone.

Common mistakes

  1. Forgetting the colon. Writing this line:

    if score > 5
    

    gives:

    SyntaxError: expected ':'
    

    Every if, elif, and else line ends with a colon.

  2. Not indenting the block. The following code stops before it runs:

    if 3 > 2:
    print("yes")
    
    IndentationError: expected an indented block after 'if' statement on line 1
    

    Indent the line under the if, usually by four spaces.

  3. Using two separate if statements where you need elif. Each if is checked on its own, so both can run. The following check fails:

    points = 95
    if points >= 90:
        grade = "A"
    if points >= 80:
        grade = "B"
    assert grade == "A"
    
    AssertionError
    

    The second if is also True, so it replaces "A" with "B". Use elif for the second condition.

  4. Writing = instead of == in a condition. The line if score = 90: gives:

    SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
    

    A condition compares values, so use ==.

Practice

  1. Set age = 16. Write an if and else that sets status to "adult" when age is 18 or more, and to "minor" otherwise. Assert that status is "minor".
  2. Set is_raining = True. Write an if and else that sets plan to "stay in" when it is raining and to "go out" when it is not. Assert that plan is "stay in".
  3. Set number = -4. Write an if, elif, and else that sets sign to "positive", "zero", or "negative". Assert that sign is "negative".
  4. Set hour = 22. Use if, elif, and else to set part to "morning" for hour < 12, "afternoon" for hour < 18, "evening" for hour < 22, and "night" otherwise. Assert that part is "night".
  5. Stretch: a year is a leap year when it is divisible by 4 and not by 100, or when it is divisible by 400. Use an if and else to set leap to True or False for year = 2024. Assert that leap is True. Then repeat the check for year = 1900 and assert that leap is False.
Solution
  1. python age = 16 if age >= 18: status = "adult" else: status = "minor" assert status == "minor"

  2. python is_raining = True if is_raining: plan = "stay in" else: plan = "go out" assert plan == "stay in"

  3. python number = -4 if number > 0: sign = "positive" elif number == 0: sign = "zero" else: sign = "negative" assert sign == "negative"

  4. python hour = 22 if hour < 12: part = "morning" elif hour < 18: part = "afternoon" elif hour < 22: part = "evening" else: part = "night" assert part == "night"

  5. ```python year = 2024 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: leap = True else: leap = False assert leap

year = 1900 if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0: leap = True else: leap = False assert not leap ```

The year 1900 is divisible by 100 but not by 400, so it is not a leap year.

Recap

  • An if block runs when its condition is True. elif adds another condition, and else covers all remaining cases.
  • Python checks the branches from top to bottom and runs at most one of them.
  • Indentation decides which lines belong to a block. A missing colon or missing indentation is a syntax error.

Sources