If, Elif, Else — Python

if condition: runs the indented block below it when the condition is True. elif (else if) is only checked when every condition above it is False, and else…

So far your programs have always run in a straight line: every line runs from top to bottom, whatever the values are. A real till does not work like that. A $120 purchase gets a discount, but a $20 purchase gets nothing. So the program must be able to choose.

Mr. Darto has put a discount rule on the stall's wall: "Spend $100 or more, 15% off. $50 or more, 10% off. $25 or more, 5% off. Below that, no discount." He reads it from the top and stops at the first line that matches. Python chooses in the same way, with if, elif and else. Each line of the rule is written as one condition (for example "the total is $100 or more"), and Python stops at the first condition that matches. Choosing a path based on a condition is called branching.

In the exercise, you write the branching yourself. In the Editor, the body of the function grade(score) is still just pass, and that pass is what you replace with if/elif/else. Functions and pass are explained in the def and return section below.

if, elif, else

Here is Mr. Darto's discount rule in Python:

total = 89

if total >= 100:
    print("15% off")
elif total >= 50:
    print("10% off")
elif total >= 25:
    print("5% off")
else:
    print("No discount")

The output is 10% off. Here is how Python checks it for total = 89, line by line:

Line Condition Result What happens
if total >= 100: 89 >= 100 False its block is skipped
elif total >= 50: 89 >= 50 True its block runs, printing 10% off
elif total >= 25: not checked a match was already found
else: not checked a match was already found

Indentation marks a block

Only the indentation (the spaces at the start of a line) marks what is inside a block. A line that moves back to the left is outside the block, so it runs whatever the condition gives. If you already know JavaScript: Python does not use curly braces for blocks. The code below shows what happens when you forget to indent the contents of a block. Look at line 3 (def and return are explained below):

def discount(total):
    if total >= 100:
    return 15

The result is an error:

  File "/home/darto/stall.py", line 3
    return 15
    ^^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

The message means: after the if on line 2, Python expects an indented block. But line 3 starts at the same position as the if.

The order of elif matters

Now the rule is in reverse order, starting with "$25 or more, 5% off". Before you look at the output, guess: what discount does a $120 purchase get?

total = 120

if total >= 25:
    print("5% off")
elif total >= 50:
    print("10% off")
elif total >= 100:
    print("15% off")

The output is 5% off, even though a $120 purchase should get 15%. The first condition, 120 >= 25, is already True. Python stops there, and the two conditions after it are never checked. No error tells you, but the result is wrong.

To avoid this: when the conditions use >=, start from the biggest threshold (the limit a value must reach) and go down. One more thing: >= includes the threshold itself, so a purchase of exactly $50 gets 10%. If you use > instead, a purchase of exactly $50 only gets 5%.

Wrapping it in a function: def and return

The discount rule is used again and again, so it is practical to wrap it in a function (a named piece of code that you can call many times):

def discount(total):
    if total >= 100:
        return 15
    elif total >= 50:
        return 10
    elif total >= 25:
        return 5
    else:
        return 0

print(discount(120))     # 15
print(discount(89))      # 10
print(discount(50))      # 10
print(discount(20))      # 0

This lesson's exercise uses the same pattern for exam scores: grade(score) returns "A", "B", "C", "D" or "E". In the Editor, the body of grade is still just pass, so if you run it as it is, all that comes out is None four times. Delete the pass line and write an if/elif/else chain in its place, like discount above: start at score >= 90, go down to 80, 70 and 60, then else for the rest. Each return is indented 4 spaces deeper than its condition. If you forget the : at the end of an if or elif, Python points at that line.

Truthy and falsy

An if doesn't need a comparison. Any value can be a condition:

note = ""
if note:
    print(f"Note: {note}")
else:
    print("No note")

The output is No note, because note holds empty text and if treats empty text as False. Values treated as False are called falsy: False, None, 0, 0.0, "" (empty text), [] (an empty list) and other empty collections such as {} (an empty dictionary, covered in the Dictionary lesson). In short, zero and all empty values are treated as False. Every other value is called truthy and is treated as True. This includes "0" and " " (text that holds a space), because the text isn't empty.

An if on one line

For example, to set the delivery fee:

delivery_fee = 0 if total >= 50 else 10

The form is value_if_True if condition else value_if_False. With total = 89, the condition is True, so delivery_fee holds 0. Use this form to choose one value, not to run several lines.

⚠️ The wrong branch, or no branch at all

TL;DR: if condition: runs the indented block below it when the condition is True. elif (else if) is only checked when every condition above it is False, and else catches the rest. Only the block of the first condition that is True runs, so with >=, put the biggest threshold first. An indentation of 4 spaces marks a block, and a block you forget to indent causes IndentationError: expected an indented block. def name(param): makes a function, and return sends its result back. Falsy (values treated as False in a condition): False, None, 0, "", [] and other empty collections such as {} (an empty dictionary). An if on one line: "Pass" if score >= 70 else "Fail".

⚡ Pick one path

Write:

total = 89

if total >= 100:
    print("15% off")
elif total >= 50:
    print("10% off")
elif total >= 25:
    print("5% off")
else:
    print("No discount")

Meaning: Each condition ends with :, and its block (the lines below it) is indented 4 spaces. elif is short for else if: it's only checked when every condition above it is False. else catches the rest. Only the block of the first condition that's True runs, so here the output is 10% off.

⚡ The order of elif matters

Guess first: the conditions above are in reverse order, starting with if total >= 25:. What discount does a $120 purchase get?

Only 5%, when it should be 15%. The first condition is already True, so Python stops there. No error tells you.

Meaning: When the conditions use >=, start from the biggest threshold and go down.

In the exercise, the function grade(score) only holds pass (which means "nothing here yet"). Replace pass with if/elif/else, starting from score >= 90, then down to 80, 70 and 60.

⚡ Empty values count as False

Guess first: note = "". Does the block under if note: run?

No. Empty text counts as False, so the else block runs.

Meaning: Any value can be a condition. False, None, 0, "" (empty text), [] (an empty list) and other empty collections such as {} (an empty dictionary, taught later) count as False (falsy). Everything else is truthy, including "0", because that text isn't empty.

What you will learn