Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

Python  Module 3 – Control flow: decisions, loops and pattern matching

Decisions with if, elif and else

Write if, elif and else chains that cover every case, choose between two values in one line, and avoid the classic x == 1 or 2 mistake in Python.

  • Beginner
  • 25 minutes
  • Examples run with Python 3.14.8 and Pyodide 314.0.7
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Write if, elif and else chains that run exactly one block for every case
  • Order the tests of a chain from the narrowest to the widest and test each boundary
  • Avoid conditions such as x == 1 or 2, which are true for every value
  • Use conditional expressions for simple choices between two values
  • Rewrite nested conditions as guard clauses that return early

Before you start

What you’ll learn · Before you start

What you will learn

  • Write if, elif and else chains that run exactly one block for every case
  • Order the tests of a chain from the narrowest to the widest and test each boundary
  • Avoid conditions such as x == 1 or 2, which are true for every value
  • Use conditional expressions for simple choices between two values
  • Rewrite nested conditions as guard clauses that return early

Before you start

On this page

Almost every useful program has to choose: charge one price or another, accept an answer or ask again, print a warning or stay quiet. A bill for 80 units of electricity must take one formula out of three, and with two tests in the wrong order it comes out as 200 instead of 240, without any error. Python’s if statement runs a block of code only when a condition is true. Add elif and else and you can describe several cases, of which Python runs exactly one.

Below you can step through real runs and see which tests Python makes and which block it runs. You will write chains that cover every case, pick one of two values in a single line, flatten nested checks, and catch the two mistakes that make a chain answer wrongly without a word: tests in the wrong order, and x == 1 or 2.

An if runs its block only when the condition is true

An if statement starts with the word if, a condition and a colon. The lines under it that are indented further form its block: The lines indented under a line that ends with a colon, such as an if, elif, else, while or for line. The block ends at the first line indented less, and it cannot be empty: write pass when it has nothing to do yet., and they run only when the condition is true. An else: line at the same indentation as the if starts a second block, for when the condition is false. Step through it: the lit line has just run, and the numbered chip marks the line that runs next.

Interactive · line by line Which lines an if with an else runs Step through the program. The lit line has just run and the numbered chip marks the line that runs next; watch which lines Python skips.

Program · heat_warning.py

temperature = 41

if temperature > 40:
    print("Heat warning")
    print("Carry water")
else:
    print("A normal day")

print("Forecast done")

Variables

After line 9: temperature is 41.temperature41
  • changed in this step

Printed so far

Heat warning
Carry water
Forecast done

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 6 steps are listed below.

Line run 9
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. temperature = 41 sets temperature to 41.
  3. Line 3. temperature > 40 is true (temperature is 41), so the block under if temperature > 40: runs. The two lines indented under the if are its block. Python knows where the block ends from the indentation alone: there are no braces and no end.
  4. Line 4. print("Heat warning") prints Heat warning.
  5. Line 5. print("Carry water") prints Carry water.
  6. Line 9. print("Forecast done") prints Forecast done. That was the last line, so the program ends. Key point The else block was skipped. Line 9 is not indented, so it belongs to neither block and runs whatever the temperature is.

The temperature is above 40, so both indented lines under if ran and the else block was skipped. The last line is not indented at all, so it is not part of either block: it runs whatever the temperature is. Change 41 to 25 with Edit and run it again to see the other path.

Three rules make this work:

  • The indentation is the block. Python has no braces or end keywords; a block lasts until a line that is indented less. PEP 8, Python’s style guide, asks for four spaces per level.
  • A block cannot be empty. When you have nothing to put in one yet, write pass, a statement that does nothing, or ..., which people often use the same way.
  • Tabs and spaces do not mix. If some lines are indented with tabs and others with spaces in a way whose meaning depends on how wide a tab is, Python stops with a TabError. Let your editor indent with spaces only.

Forget to indent, and the program does not run at all:

An if without its block Python · missing_block.py
temperature = 41
if temperature > 40:
print("Heat warning")

Output (exit status 1)

Printed as an error (standard error)

  File "missing_block.py", line 3
    print("Heat warning")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 2

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 missing_block.py

The message names the line of the if that is missing its block. Like any syntax error, it stops the whole file before the first line runs, so not even the assignment on line 1 happened.

Any value can be a condition

A condition is usually a comparison such as temperature > 40, which is either True or False. But if accepts any value and asks whether it counts as true. False, None, zero (0, 0.0) and empty strings, lists and other empty containers count as false; every other value counts as true. Values that count as false are called falsy: A value that counts as false in a condition. The falsy values are None, False, zero of any number type, and empty strings and collections such as "", [] and {}. More in “Booleans, None, truthiness and comparisons”, and all the others truthy: A value that counts as true in an if or while condition and in and, or and not. Every value is truthy except the falsy ones, so "0", [0] and " " are truthy. More in “Booleans, None, truthiness and comparisons”. So if name: means “if name is not an empty string”, a short form you will see often. Keep this rule in mind: it explains the classic if mistake shown in the section on x == 1 or 2 below.

Checkpoint

Check: An if and its block

  1. Question 1 of 2 heat_warning.py is run again with temperature = 25. What does it print?

    Choose one answer.

    A hint

    Which block runs when the condition is false, and which line belongs to neither block?

    Show the answer: Question 1 of 2

    Answer: A normal day, then Forecast done

    With 25 the test temperature > 40 is false, so Python skips the two lines of the if block and runs the else block. The last line is indented less than both blocks, so it is not part of either and always runs.

  2. Question 2 of 2 You want an if whose block does nothing yet, as a placeholder you will fill in later. Which version runs?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: if ready: with an indented pass under it

    A block needs at least one statement. Comments and blank lines are not statements, so write pass (or ...) in a block that has nothing to do yet.

An elif chain runs only the block of the first true test

elif, short for “else if”, adds more conditions between the if and the else. Python tests them from the top, runs the block of the first one that is true, and skips the rest of the chain without even testing it. When no condition is true, the else block runs, if there is one.

Suppose electricity is billed in slabs, where each band of units has its own rate. The chain below works out a month’s charge with made-up rates: 3 for each of the first 100 units, 5 for each of the next 200 and 8 for every unit above 300. Step through a bill of 250 units and watch which tests Python makes:

Interactive · line by line One bill of 250 units through the slab chain Step through the chain and watch which tests Python makes. The lit line has just run; the chip marks the line that runs next.

Program · slab_chain.py

units = 250

if units <= 100:
    charge = units * 3
elif units <= 300:
    charge = 300 + (units - 100) * 5
else:
    charge = 1300 + (units - 300) * 8

print(units, "units cost", charge)

Variables

After line 10: units is 250; charge is 1050.units250charge1050
  • changed in this step

Printed so far

250 units cost 1050

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 6 steps are listed below.

Line run 10
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. units = 250 sets units to 250.
  3. Line 3. units <= 100 is false (units is 250), so Python tests the next condition.
  4. Line 5. units <= 300 is true (units is 250), so the block under elif units <= 300: runs. This elif needs no lower limit. Python tests it only after units <= 100 was false, so every value that reaches it is already above 100.
  5. Line 6. charge = 300 + (units - 100) * 5 sets charge to 1050.
  6. Line 10. print(units, "units cost", charge) prints 250 units cost 1050. That was the last line, so the program ends. Key point Exactly one block ran. Once units <= 300 was true, Python skipped the else block without a look. Press Edit, try 80 and then 450, and run each.

Python tested units <= 100 and found it false, tested units <= 300 and found it true, ran that block and went straight to the print(). It never reached the else. A bill must be worked out for many customers, so the next program puts the same chain in a function and tries it on six bills.

def and return

From here on, most examples put the decision inside a function, so that the program can try it with several inputs: def energy_charge(units): gives the block a name, and return hands back the result and ends the function at once. Functions get a module of their own later in this track.

Electricity slabs with if, elif and else Python · slab_bill.py
# A month's energy charge, worked out slab by slab: the first 100
# units cost 3 each, the next 200 cost 5 each, and every unit above
# 300 costs 8. The rates are made up for this example.

def energy_charge(units):
    if units <= 100:
        return units * 3
    elif units <= 300:
        return 100 * 3 + (units - 100) * 5
    else:
        return 100 * 3 + 200 * 5 + (units - 300) * 8


print("80 units:", energy_charge(80))
print("100 units:", energy_charge(100))
print("101 units:", energy_charge(101))
print("300 units:", energy_charge(300))
print("301 units:", energy_charge(301))
print("450 units:", energy_charge(450))

Output

80 units: 240
100 units: 300
101 units: 305
300 units: 1300
301 units: 1308
450 units: 2500

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 slab_bill.py

Flowchart of the slab chain: units <= 100 is tested first, then units <= 300, and the else block takes the rest.units <= 100?if blockunits × 3units <= 300?elif block300 +(units − 100) × 5else block1300 +(units − 300) × 8truefalsetruefalse

How the if, elif and else chain of slab_bill.py picks one block

Text description of the diagram

The diagram is a flowchart of energy_charge(units), read from the top.

  1. Python first tests units <= 100. When it is true, the if block runs (units × 3) and nothing else in the chain is tested.
  2. When it is false, Python tests units <= 300. When that is true, the elif block runs: 300 + (units − 100) × 5.
  3. When both tests are false, the else block runs: 1300 + (units − 300) × 8.

Each path ends in exactly one block, so every number of units gets exactly one of the three formulas.

Read the chain the way Python does. For 450 units, units <= 100 is false, units <= 300 is false, so the else block runs. For 250 units the second test is true, and Python never looks at the else. The elif needs no lower limit: it is tested only after units <= 100 was false, so every value that reaches it is already above 100. Written on its own, the same test would be the chained comparison: Comparisons written in a row, such as 0 <= marks <= 100, which means 0 <= marks and marks <= 100, with marks evaluated only once. More in “Booleans, None, truthiness and comparisons” 100 < units <= 300.

The program tries 100 and 101, and 300 and 301, on purpose. Mistakes in chains like this hide at the boundary value: A value at the edge of a case, such as 100 and 101 when the first slab of a bill ends at 100 units. Mistakes with < and <= show only there, so tests try each edge and the value just past it., where < and <= give different answers, so test the value on each edge and the one just past it: at 301 units, exactly one unit is charged at the top rate, so the charge is 1300 + 8. And because the chain ends with else, every number of units gets a charge: no case falls through the gaps.

Key idea

Python tests a chain from the top and runs only the block of the first test that is true; an else at the end catches every case the tests above it missed.

An else ends the chain

An else block must be the last part of its chain. Put an elif after it and Python refuses the file:

elif after else Python · elif_after_else.py
units = 120
if units <= 100:
    print("First slab")
else:
    print("Above 100 units")
elif units <= 300:
    print("Second slab")

Output (exit status 1)

Printed as an error (standard error)

  File "elif_after_else.py", line 6
    elif units <= 300:
    ^^^^
SyntaxError: 'elif' block follows an 'else' block

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 elif_after_else.py

Version note

New in Python 3.14: this mistake gets its own message, 'elif' block follows an 'else' block. Python 3.13 and older report it only as invalid syntax. To fix it, move the else block to the end of the chain.

When you compare one value with many fixed values, such as commands typed by a user, the match statement from a later lesson of this module can be easier to read than a long elif chain.

Checkpoint

Check: The first true test of a chain

  1. Question 1 of 2 In the slab chain, which tests does Python make for a bill of 80 units?

    Choose one answer.

    A hint

    Python stops testing as soon as one test is true.

    Show the answer: Question 1 of 2

    Answer: Only units <= 100

    A chain is tested from the top and stops at the first true test. For 80 units that is the very first one, so the elif and the else are never reached.

  2. Question 2 of 2 With the slab rates of the lesson (3 for each of the first 100 units, 5 for each of the next 200, 8 above 300), what does energy_charge(120) return?

    Type a number.

    A hint

    120 is above 100, so the elif block works out the charge.

    Show the answer: Question 2 of 2

    Answer: 400

    120 <= 100 is false and 120 <= 300 is true, so the elif block runs: 300 + (120 − 100) × 5 = 300 + 100 = 400. The first 100 units cost 300, and the 20 units after them cost 5 each.

The order of the tests decides which block runs

The order of the tests matters as much as the tests themselves. Here the two conditions of the same chain are swapped. Step through a bill of 80 units and watch which test is true first:

Interactive · line by line The same slabs with the wider test first Step through a bill of 80 units and watch which test comes out true first.

Program · wrong_order.py

# The slabs of slab_bill.py with the two
# tests swapped: the wider one is first.
units = 80

if units <= 300:
    charge = 300 + (units - 100) * 5
elif units <= 100:
    charge = units * 3
else:
    charge = 1300 + (units - 300) * 8

print(units, "units cost", charge)

Variables

After line 12: units is 80; charge is 200.units80charge200
  • changed in this step

Printed so far

80 units cost 200

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 5 steps are listed below.

Line run 12
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 3.
  2. Line 3. units = 80 sets units to 80.
  3. Line 5. units <= 300 is true (units is 80), so the block under if units <= 300: runs. The bug 80 is at most 300 too, so the wider test catches it first and the second slab's formula runs. The narrower test below it never gets a turn.
  4. Line 6. charge = 300 + (units - 100) * 5 sets charge to 200.
  5. Line 12. print(units, "units cost", charge) prints 80 units cost 200. That was the last line, so the program ends. The bill says 200, where the first slab's 80 × 3 = 240 was meant, and nothing warns you. Press Edit, swap the two tests back and run it: 240.

80 units now cost 200 instead of 240. units <= 300 is also true for 80, so the second slab’s formula runs, and the elif units <= 100 block can never run for any number. Put the narrowest test first, or give every test both of its limits so that the order no longer matters.

The same slip hides in any ladder of thresholds. With if score >= 50: above elif score >= 70:, a score of 75 is reported as a pass and never as a merit, because the wider test answers first. When the tests go upwards, start from the top of the ladder: score >= 70 before score >= 50.

Electricity Bill & Appliance Cost Calculator Enter the slabs of this example (up to 100 units at 3, up to 300 at 5, above at 8) and compare its slab-by-slab breakdown with what slab_bill.py prints.

Checkpoint

Check: The order of the tests

  1. Question 1 of 2 A grade is "merit" from 70 marks and "pass" from 50. Which chain gives a score of 75 a merit?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: if score >= 70: merit, elif score >= 50: pass

    With thresholds that go upwards, test the highest one first. Each later test is then reached only by the scores that failed every test above it.

  2. Question 2 of 2 Which print in this chain can never run, whatever number n is?

    Read the code, then choose one answer.

    if n > 0:
        print("positive")
    elif n > 10:
        print("big")
    elif n == 0:
        print("zero")
    else:
        print("negative")
    Show the answer: Question 2 of 2

    Answer: print("big")

    A test that is wider and comes earlier hides every narrower test below it. n > 10 is reached only after n > 0 was false, and then n is 0 or less, so it can never be above 10. Test n > 10 first to fix it.

Each side of or must be a whole comparison

Here is a check for weekend prices that looks right and is not:

A condition that is always true Python · weekend_bug.py
day = "Tue"

if day == "Sat" or "Sun":
    print("Weekend price")
else:
    print("Weekday price")

print(day == "Sat" or "Sun")

if day == "Sat" or day == "Sun":
    print("Weekend price")
else:
    print("Weekday price")

if day in ("Sat", "Sun"):
    print("Weekend price")
else:
    print("Weekday price")

Output

Weekend price
Sun
Weekday price
Weekday price

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 weekend_bug.py

On a Tuesday the first if still printed “Weekend price”. Python reads day == "Sat" or "Sun" as (day == "Sat") or "Sun", because == is applied before or. Then or works like this: if its left side counts as true, the result is the left side; otherwise the result is the right side. day == "Sat" is False, so the whole condition is the string "Sun", as the second line of output shows, and a non-empty string counts as true. The if block runs on every day of the week.

Step through the same condition on its own, stored in a variable, and watch the value that or gives back:

Interactive · line by line What day == "Sat" or "Sun" gives on a Tuesday Step through and watch the value stored in weekend. The lit line has just run; the chip marks the line that runs next.

Program · or_trap.py

day = "Tue"
weekend = day == "Sat" or "Sun"
print(weekend)
if weekend:
    print("Weekend price")
else:
    print("Weekday price")

Variables

After line 5: day is 'Tue'; weekend is 'Sun'.day'Tue'weekend'Sun'
  • changed in this step

Printed so far

Sun
Weekend price

Every step was recorded from a run with Python 3.14.8 on macOS 26 arm64.

The drawing shows the variables when the program ends, and the program's 6 steps are listed below.

Line run 5
Next line end
Every step as text
  1. Start. No line has run yet, so there are no variables. Python starts with line 1.
  2. Line 1. day = "Tue" sets day to 'Tue'.
  3. Line 2. weekend = day == "Sat" or "Sun" sets weekend to 'Sun'. The bug == is applied before or, so this is (day == "Sat") or "Sun". The comparison is False, so or gives back its right side, the string "Sun".
  4. Line 3. print(weekend) prints Sun.
  5. Line 4. weekend is true (weekend is 'Sun'), so the block under if weekend: runs. A non-empty string counts as true, so the weekend block runs on a Tuesday, and on every other day as well.
  6. Line 5. print("Weekend price") prints Weekend price. That was the last line, so the program ends.

The last two tests in weekend_bug.py are the fixes. Either compare the variable each time, day == "Sat" or day == "Sun", or ask whether it is one of several values with in: day in ("Sat", "Sun"). The second form stays short when the list grows. The same trap catches numbers: if x == 1 or 2: is always true, while if x in (1, 2): is what was meant.

Key idea

Each side of or is a condition of its own: compare the variable on both sides, or ask day in ("Sat", "Sun").

Checkpoint

Check: The x == 1 or 2 trap

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    x = 3
    print(x == 1 or 2)
    Show the answer: Question 1 of 2

    Answer: 2

    == is applied first, so the expression is (x == 1) or 2. The left side is False, so or gives back the right side, 2, which counts as true in an if. That is why if x == 1 or 2 runs for every x.

  2. Question 2 of 2 Which condition is true exactly when x is 1 or 2?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: x in (1, 2)

    Compare the variable on each side of or, x == 1 or x == 2, or test membership with x in (1, 2). Both are true exactly for 1 and 2.

A conditional expression picks one of two values

When all you need is one of two values, a conditional expression: An expression of the form a if condition else b. It evaluates the condition and gives a when the condition is true and b otherwise, evaluating only the side it picks. More in “Booleans, None, truthiness and comparisons” does it inside a single line: value_if_true if condition else value_if_false.

Conditional expressions Python · one_line_choice.py
age = 16
label = "adult" if age >= 18 else "minor"
print(age, label)

tickets = 1
print(tickets, "ticket" if tickets == 1 else "tickets")
tickets = 3
print(tickets, "ticket" if tickets == 1 else "tickets")

# Only the chosen side is worked out, so no division happens here.
total = 0
count = 0
average = total / count if count > 0 else 0
print("Average:", average)

Output

16 minor
1 ticket
3 tickets
Average: 0

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 one_line_choice.py

Python works out the condition first and then only the side it chose. That is why the last example is safe: count is 0, so total / count is never calculated and there is no ZeroDivisionError.

Use conditional expressions for short choices between two values, like a label or a word that depends on a number. When each case does something, when there are more than two cases, or when you are tempted to put one conditional expression inside another, write an if statement instead: it is easier to read and to change.

Checkpoint

Check: Conditional expressions

  1. Question 1 of 2 What does this print?

    Read the code, then choose one answer.

    n = 7
    print("even" if n % 2 == 0 else "odd")
    Show the answer: Question 1 of 2

    Answer: odd

    a if condition else b gives a when the condition is true and b otherwise. 7 is odd, so the condition is false and the result is "odd".

  2. Question 2 of 2 In which case is an if statement clearer than a conditional expression?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Paid orders send a receipt by email and unpaid ones write a reminder to a log

    Use a conditional expression to pick one of two values. When the cases do different things, when there are more than two, or when one expression would nest inside another, write an if statement.

Guard clauses keep a function flat

Conditions inside conditions push the main work further and further to the right. Both versions of withdraw below give the same answers; compare how they read:

Nested conditions and guard clauses

Nested · withdraw_nested.py

def withdraw(balance, amount):
    if amount > 0:
        if amount <= balance:
            return f"Paid {amount}, {balance - amount} left"
        else:
            return "Not enough money"
    else:
        return "The amount must be more than 0"


print(withdraw(500, 200))
print(withdraw(500, 900))
print(withdraw(500, -5))

Output

Paid 200, 300 left
Not enough money
The amount must be more than 0

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 withdraw_nested.py

Guard clauses · withdraw_guard.py

def withdraw(balance, amount):
    if amount <= 0:
        return "The amount must be more than 0"
    if amount > balance:
        return "Not enough money"
    return f"Paid {amount}, {balance - amount} left"


print(withdraw(500, 200))
print(withdraw(500, 900))
print(withdraw(500, -5))

Output

Paid 200, 300 left
Not enough money
The amount must be more than 0

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 withdraw_guard.py

The second version checks for each problem first and returns straight away. Because return ends the function, the cases that get past both checks need no else, and the normal case sits at the bottom, not indented any further. These early checks are called guard clause: A test at the top of a function that returns at once when an input is wrong or a case is special, so the main work below it needs no else and no extra indentation.. They keep each rule on its own two lines, so adding a third rule (a daily limit, say) means adding two lines rather than another level of nesting.

The order of the guards is the order of the questions you would ask at a counter: is the request valid at all, and only then, can it be paid? A guard that tests amount > balance before amount <= 0 would still give the right answers here, but the first question to fail is the one the caller hears about, so put the cheapest and most basic checks first.

Checkpoint

Check: Guard clauses

  1. One question withdraw must also refuse amounts above 10,000 a day. Where does the new rule go in the version with guard clauses?

    Choose one answer.

    A hint

    What does each guard do when its test is true?

    Show the answer: One question

    Answer: As a third if that returns a message, before the last return line

    Each guard clause is one test and one early return, so a third rule is a third guard: if amount > 10_000: return a message. The normal case stays at the bottom, as flat as before.

Python Online Compiler Write your own if, elif and else chains in a full editor and run them in your browser.

Practise: price a cinema ticket

The exercise brings the main ideas of this lesson together: a guard clause for the free tickets, one chain whose tests go from the narrowest case to the widest, and a test with in for the weekend. Write it in the editor below; its sample tests try each age band on both sides of its edges, and a first hint is there if you get stuck.

Exercise · Easy · Python

Work out the price of a cinema ticket

A small cinema prices its tickets by age, gives students a discount and charges more at weekends. Write ticket_price(age, is_student, day), which returns the price of one ticket as a whole number.

  • age is a whole number of years, 0 or more; is_student is True or False; day is one of "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" and "Sun".
  • Children under 3 go free: their ticket is 0 on every day.
  • Children from 3 to 12 pay 120.
  • Visitors aged 60 or more pay 160.
  • Students aged 13 to 59 pay 180.
  • Everyone else pays 240.
  • On "Sat" and "Sun", every ticket that is not free costs 40 more.

A student who is also a child or a senior pays the child or senior price, so ticket_price(10, True, "Mon") is 120 and ticket_price(65, True, "Mon") is 160, while ticket_price(25, True, "Sun") is 220.

Starter code · tickets.py

def ticket_price(age, is_student, day):
    """Return the price of one ticket (see the rules in the prompt)."""
    price = 240
    return price
The sample tests · test_tickets.py
from tickets import ticket_price


def test_children():
    """children under 3 go free and children from 3 to 12 pay 120"""
    assert ticket_price(0, False, "Mon") == 0
    assert ticket_price(2, False, "Wed") == 0
    assert ticket_price(3, False, "Mon") == 120
    assert ticket_price(12, False, "Thu") == 120


def test_adults_and_seniors():
    """adults pay 240 and visitors aged 60 or more pay 160"""
    assert ticket_price(13, False, "Mon") == 240
    assert ticket_price(59, False, "Fri") == 240
    assert ticket_price(60, False, "Fri") == 160
    assert ticket_price(85, False, "Tue") == 160


def test_students():
    """students from 13 to 59 pay 180, others the child or senior price"""
    assert ticket_price(13, True, "Mon") == 180
    assert ticket_price(59, True, "Thu") == 180
    assert ticket_price(10, True, "Mon") == 120
    assert ticket_price(65, True, "Mon") == 160


def test_weekend():
    """Saturday and Sunday tickets cost 40 more, except free ones"""
    assert ticket_price(30, False, "Sat") == 280
    assert ticket_price(25, True, "Sun") == 220
    assert ticket_price(8, False, "Sun") == 160
    assert ticket_price(70, False, "Sat") == 200
    assert ticket_price(1, False, "Sat") == 0


def test_weekdays():
    """no weekday costs extra"""
    for day in ("Mon", "Tue", "Wed", "Thu", "Fri"):
        assert ticket_price(30, False, day) == 240
A hint

Handle the free tickets first and return 0 straight away. Then pick the base price with one if/elif/else chain, testing the ages in order (once age <= 12 has been ruled out, the next tests only see visitors of 13 or more), and add the weekend charge afterwards with a separate if day in ("Sat", "Sun"):, so that it is written only once.

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

When the tests pass, try the questions on decisions. Each one checks a single idea of this lesson, and picking a choice shows at once why it holds or where it slips:

Practice that adapts to you

Practise this lesson

14 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 14 What does this print?

    Read the code, then choose one answer.

    x = 5
    if x > 10:
        print("big")
        print("very big")
    print("done")
    Show the answer: Question 1 of 14

    Answer: done

    The block is every line indented under the if. 5 > 10 is false, so the two prints in the block are skipped, and only the unindented print("done") runs.

  2. Question 2 of 14 How does Python know which lines belong to the block of an if?

    Choose one answer.

    Show the answer: Question 2 of 14

    Answer: By their indentation; the block ends at the first line indented less

    The indentation is the block. PEP 8 asks for four spaces per level, and mixing tabs and spaces in a way that depends on the width of a tab makes Python stop with TabError.

  3. Question 3 of 14 In slab_bill.py, which formula does energy_charge(300) use?

    Choose one answer.

    Show the answer: Question 3 of 14

    Answer: The elif block: 300 + (units − 100) × 5

    300 <= 100 is false, so Python tests the elif: 300 <= 300 is true, so its block runs and the else is skipped. Exactly one block of a chain runs, which is why the output shows 1300 for 300 units.

  4. Question 4 of 14 An if with two elif parts and an else runs. How many of its four blocks run?

    Choose one answer.

    Show the answer: Question 4 of 14

    Answer: Exactly one

    A chain is one decision. With an else at the end, exactly one block runs for every value; without it, a value that fails every test runs none.

  5. Question 5 of 14 You may test the slab chain with four bills only. Which four values check its boundaries?

    Choose every answer that is right.

    Show the answer: Question 5 of 14

    Answer:

    • 100
    • 300
    • 101
    • 301

    Mistakes with < and <= show only at the edges, so test the value on each edge and the one just past it: 100 and 101, 300 and 301. Values in the middle of a slab give the same bill either way.

  6. Question 6 of 14 What does this print?

    Read the code, then choose one answer.

    score = 75
    if score >= 50:
        print("pass")
    elif score >= 70:
        print("merit")
    else:
        print("fail")
    Show the answer: Question 6 of 14

    Answer: pass

    Python runs the block of the first condition that is true and skips the rest. 75 >= 50 is already true, so "merit" can never be printed by this chain: the wider test comes first. Testing score >= 70 first fixes it.

  7. Question 7 of 14 The tests of a chain overlap, such as units <= 100 and units <= 300. Which order is right?

    Choose one answer.

    Show the answer: Question 7 of 14

    Answer: The narrowest test first, so each wider test sees only what is left

    Put the narrowest test first, or give every test both of its limits, such as 100 < units <= 300, so that the order no longer matters.

  8. Question 8 of 14 What does weekend_bug.py print, with day = "Tue"?

    What does this program print? Choose one answer.

    day = "Tue"
    
    if day == "Sat" or "Sun":
        print("Weekend price")
    else:
        print("Weekday price")
    
    print(day == "Sat" or "Sun")
    
    if day == "Sat" or day == "Sun":
        print("Weekend price")
    else:
        print("Weekday price")
    
    if day in ("Sat", "Sun"):
        print("Weekend price")
    else:
        print("Weekday price")
    Show the answer: Question 8 of 14

    Answer: it prints

    Weekend price
    Sun
    Weekday price
    Weekday price

    day == "Sat" or "Sun" means (day == "Sat") or "Sun". The comparison is False, so or gives back "Sun", which the second line prints; a non-empty string counts as true, so the first if takes the weekend branch. The two fixed tests compare day itself and print "Weekday price".

  9. Question 9 of 14 Which of these conditions are true exactly when day is "Sat" or "Sun"?

    Choose every answer that is right.

    Show the answer: Question 9 of 14

    Answer:

    • day in ("Sat", "Sun")
    • day == "Sat" or day == "Sun"

    day == "Sat" or day == "Sun" and day in ("Sat", "Sun") both compare day with each of the two values. day == "Sat" or "Sun" is always true, as in the lesson. In day == ("Sat" or "Sun") the brackets come first: "Sat" or "Sun" is just "Sat" (the left side counts as true, so or returns it), so that condition is true only on Saturdays.

  10. Question 10 of 14 if colour == "red" or "green" or "blue": is meant to accept three colours. What should it be?

    Choose one answer.

    Show the answer: Question 10 of 14

    Answer: if colour in ("red", "green", "blue")

    With three or more values the membership test is the clearest fix: colour in ("red", "green", "blue"). Writing colour == on every side works too, but grows with every value.

  11. Question 11 of 14 What does this print?

    Read the code, then choose one answer.

    count = 0
    average = 90 / count if count > 0 else 0
    print(average)
    Show the answer: Question 11 of 14

    Answer: 0

    A conditional expression works out its condition first and then only the side it chose. count > 0 is false, so 90 / count is never calculated and average is 0.

  12. Question 12 of 14 Which line gives label the value "adult" from 18 years and "minor" below?

    Choose one answer.

    Show the answer: Question 12 of 14

    Answer: label = "adult" if age >= 18 else "minor"

    Python's conditional expression reads value_if_true if condition else value_if_false, and both values are required.

  13. Question 13 of 14 What is a guard clause?

    Choose one answer.

    Show the answer: Question 13 of 14

    Answer: A test at the start of a function that returns at once when an input is wrong

    A guard clause checks for one problem before the main work and returns straight away when it finds it. Because return ends the function, the code below runs only for inputs that passed every guard.

  14. Question 14 of 14 This function must return "empty" for an empty list and the first item otherwise. Is the else needed?

    Read the code, then choose one answer.

    def first(items):
        if not items:
            return "empty"
        else:
            return items[0]
    Show the answer: Question 14 of 14

    Answer: No; return ends the function, so items[0] can follow the guard unindented

    After a guard clause that returns, the else is redundant: the code below it already runs only when the guard's test was false. Dropping it keeps the normal case flat.

Interview questions

Fresher · What is the difference between an if/elif chain and the same conditions written as separate if statements?

A chain is one decision: Python tests its conditions from the top, runs the block of the first one that is true, and skips everything after it, so at most one block runs, and exactly one when the chain ends with else. Separate if statements are separate decisions: Python tests every one of them, and every block whose condition is true runs. With a score of 75, if score >= 70: then elif score >= 50: prints only “merit”, while the same two tests written as two if statements print “merit” and “pass”. Use a chain when the cases exclude each other and one answer is wanted, such as a price band or a grade; then order matters, so put the narrowest test first. Use separate if statements when each check stands on its own, such as several warnings that may all apply at once.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A shop charges no delivery fee from 500, 40 from 200 to 499 and 70 below 200. Its code tests if total > 200 first, then elif total >= 500, then else. Orders of 650 are charged 40 and an order of exactly 200 is charged 70. Find both bugs, fix the chain and list the totals you would test.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Fresher to mid

    Every order on a site is charged the express-shipping fee, standard orders included. The code reads if method == "express" or "overnight":. Explain the bug as you would to a new teammate, fix it, and say how a test and a linter would have caught it.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • An if block is the indented lines after the colon; four spaces per level, never a mix of tabs and spaces. Write pass when a block has nothing to do yet.
  • In an if/elif/else chain Python runs only the first block whose condition is true; finish with else so that every case is covered, and test the values on each boundary.
  • Order the tests from the narrowest to the widest, or give each test both of its limits.
  • x == 1 or 2 is always true; write x == 1 or x == 2, or x in (1, 2).
  • a if condition else b picks one of two values and works out only the side it picks.
  • Guard clauses (check, then return early) keep functions flat and easy to extend.

Terms in this lesson

block
The lines indented under a line that ends with a colon, such as an if, elif, else, while or for line. The block ends at the first line indented less, and it cannot be empty: write pass when it has nothing to do yet.
boundary value
A value at the edge of a case, such as 100 and 101 when the first slab of a bill ends at 100 units. Mistakes with < and <= show only there, so tests try each edge and the value just past it.
guard clause
A test at the top of a function that returns at once when an input is wrong or a case is special, so the main work below it needs no else and no extra indentation.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.