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.
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.
Program · heat_warning.py
temperature = 41
if temperature > 40:
print("Heat warning")
print("Carry water")
else:
print("A normal day")
print("Forecast done") Variables
- changed in this step
Printed so far
Nothing printed yetHeat 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.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
temperature = 41setstemperatureto41. - Line 3.
temperature > 40is true (temperatureis41), so the block underif temperature > 40:runs. The two lines indented under theifare its block. Python knows where the block ends from the indentation alone: there are no braces and noend. - Line 4.
print("Heat warning")printsHeat warning. - Line 5.
print("Carry water")printsCarry water. - Line 9.
print("Forecast done")printsForecast done. That was the last line, so the program ends. Key point Theelseblock 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
endkeywords; 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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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:
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
- changed in this step
Printed so far
Nothing printed yet250 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.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
units = 250setsunitsto250. - Line 3.
units <= 100is false (unitsis250), so Python tests the next condition. - Line 5.
units <= 300is true (unitsis250), so the block underelif units <= 300:runs. Thiselifneeds no lower limit. Python tests it only afterunits <= 100was false, so every value that reaches it is already above 100. - Line 6.
charge = 300 + (units - 100) * 5setschargeto1050. - Line 10.
print(units, "units cost", charge)prints250 units cost 1050. That was the last line, so the program ends. Key point Exactly one block ran. Onceunits <= 300was true, Python skipped theelseblock 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.
# 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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.
- Python first tests units <= 100. When it is true, the if block runs (units × 3) and nothing else in the chain is tested.
- When it is false, Python tests units <= 300. When that is true, the elif block runs: 300 + (units − 100) × 5.
- 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:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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:
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
- changed in this step
Printed so far
Nothing printed yet80 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.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 3.
- Line 3.
units = 80setsunitsto80. - Line 5.
units <= 300is true (unitsis80), so the block underif 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. - Line 6.
charge = 300 + (units - 100) * 5setschargeto200. - Line 12.
print(units, "units cost", charge)prints80 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.
Checkpoint
Check: The order of the tests
Each side of or must be a whole comparison
Here is a check for weekend prices that looks right and is not:
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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:
Program · or_trap.py
day = "Tue"
weekend = day == "Sat" or "Sun"
print(weekend)
if weekend:
print("Weekend price")
else:
print("Weekday price") Variables
- changed in this step
Printed so far
Nothing printed yetSun 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.
Change the program and run it here. Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
Every step as text
- Start. No line has run yet, so there are no variables. Python starts with line 1.
- Line 1.
day = "Tue"setsdayto'Tue'. - Line 2.
weekend = day == "Sat" or "Sun"setsweekendto'Sun'. The bug==is applied beforeor, so this is(day == "Sat") or "Sun". The comparison is False, soorgives back its right side, the string "Sun". - Line 3.
print(weekend)printsSun. - Line 4.
weekendis true (weekendis'Sun'), so the block underif weekend:runs. A non-empty string counts as true, so the weekend block runs on a Tuesday, and on every other day as well. - Line 5.
print("Weekend price")printsWeekend 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
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.
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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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 · 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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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.
ageis a whole number of years, 0 or more;is_studentisTrueorFalse;dayis 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.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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.
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.
-
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.
-
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.
Key takeaways
- An
ifblock is the indented lines after the colon; four spaces per level, never a mix of tabs and spaces. Writepasswhen a block has nothing to do yet. - In an
if/elif/elsechain Python runs only the first block whose condition is true; finish withelseso 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 2is always true; writex == 1 or x == 2, orx in (1, 2).a if condition else bpicks 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
- The Python Tutorial: if Statements (Python Software Foundation)
- The Python Language Reference: The if statement (Python Software Foundation)
- The Python Language Reference: Boolean operations (Python Software Foundation)
- The Python Language Reference: Operator precedence (Python Software Foundation)
- The Python Language Reference: Conditional expressions (Python Software Foundation)
- The Python Language Reference: Indentation (Python Software Foundation)
- The Python Tutorial: pass Statements (Python Software Foundation)
- PEP 8: Style Guide for Python Code (Python Software Foundation)
- What's New In Python 3.14: improved error messages (Python Software Foundation)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress