Programming in Python / Decisions
Decisions
All 5 lessons, in order.
The unit at a glance
- Ask a true-or-false question
A fairground ride has a height bar at its gate.
- Choose a branch
A footpath reaches a garden gate with a notice.
- Handle a boundary value
Imagine a courier whose price depends on a parcel's weight.
- Combine two conditions
Here are two signs invented for this lesson.
- Trace a ticket rule
Imagine a museum that prints its ticket rule on a board.
Rules (5)
- Ask a true-or-false question
A comparison has a value on each side of a comparison operator. When both sides are numbers, or both are strings, Python works out the two sides, asks the question and gives back
TrueorFalse.<,<=,>and>=ask about order.==asks whether the two values are equal, and!=asks whether they differ.Two whole numbers are equal when they are the same number. Two strings are equal when they hold the same characters in the same order, so
"Gate" == "gate"isFalse. A string and a whole number are never equal, so"6" == 6isFalse. Asking about order between a string and a number, as in"6" < 7, stops the program with a TypeError. - Choose a branch
Write
if, a condition and a colon. Indent the block beneath it, by four spaces in this course. Python runs the block only when the condition is true. An optionalelse:line, lined up with theif, has its own indented block, which runs only when the condition is false. Lines after the whole statement, back at the left margin, run in both cases. - Handle a boundary value
In an
if,elif,elsechain Python works out the conditions in order and runs the block of the first one that is true. No later branch is tested or run. If every condition is false, theelseblock runs, and if there is noelse, no block of the chain runs.<=and>=include the value they are compared with.<and>leave it out. - Combine two conditions
When A and B are each
TrueorFalse:A and BisTrueonly if both areTrue.A or BisTrueif at least one isTrue.not AisTrueif A isFalse, andFalseif A isTrue.Without parentheses, comparisons group first, then
not, thenand, thenor. Python works out the left side ofandororfirst, and works out the right side only when the left side has not settled the answer. - Trace a ticket rule
A block may hold another
ifstatement. The inner statement's blocks are indented one level further, by four more spaces in this course. Python reaches the innerifonly when the block that holds it runs. Eachelseorelifbelongs to theifwhose line starts at the same depth.
Recipes (5)
- Ask a true-or-false question
- Say the question in words. For the boat program below, one question is whether the number of riders is more than the number of seats.
- Choose the operator that matches the words. "More than" is
>. "At least" is>=. "Fewer than" is<. "At most" is<=. "Exactly" is==. "Anything but" is!=. - Check the types. A string and a whole number are never equal, so compare a number with a number and text with text. A value that came from
input()is text. When that text is a whole number such as6,intmakes a number from it, as the second worked example shows. - Work out each side to one value. Do any arithmetic first.
- Ask the question about those two values and write
TrueorFalse.
- Choose a branch
- Write the decision as two sentences, the first starting with if and the second with otherwise. The baggage rule invented for this lesson reads: if the bag is over the weight limit, charge a fee. Otherwise, charge nothing.
- Turn the first sentence into an
ifline. Writeif, then the condition, then a colon:if weight > 23:. - On the next lines, indented by four spaces, write what happens when the condition is True.
- If something different happens otherwise, write
else:lined up withif, and indent its lines by four spaces too. - Return to the left margin for the lines that run in both cases.
- Trace the program twice, once with a value that makes the condition True and once with a value that makes it False.
- Handle a boundary value
- List the values where the rule changes. In the parcel rule they are 2 and 10.
- For each one, read the words of the rule and decide which side the value itself belongs to. The rule says up to 2, so 2 stays with the lighter parcels.
- Use
iffor the first band,eliffor each middle band andelsefor what is left. Put the conditions in order from one end of the range. The parcel program starts from the lowest cutoff. - Pick test values: each boundary value and the whole number on the other side of the change. The rule keeps 2 in the lower band, so the other side starts at 3. It keeps 10 in the middle band, so the other side starts at 11. The test values are 2, 3, 10 and 11.
- Work out the expected price for each test value by hand, from the words of the rule.
- Run or trace the program with each test value and compare. A mismatch at a boundary points to
<against<=or to the order of the conditions.
- Combine two conditions
- Write the rule in words and underline each joining word: and, or, not.
- Write each part as a complete condition. A part is a comparison with its own left side, operator and right side, such as
height >= 120, or a name that already holdsTrueorFalse, such ashas_ticket. - Where the rule negates a part, write
notin front of that part, such asnot has_coat. - Join the parts with
andwhere both must hold and withorwhere one is enough. - If the rule mixes
andwithor, put parentheses around the part the rule treats as one group, as in(member or total > 50) and coupon. - Fill in a small table with one row for each case of the parts, True or False, and work out the whole condition for every row.
- Trace a ticket rule
- Write the inputs for one test case at the top of a sheet, with the output you expect from the rule in words.
- Go down the program one line at a time. At an assignment, record the new value of the name.
- At an
iforelifline, work out the condition with the current values and write True or False beside it. - If it is True, move into the block beneath it. If it is False, skip every line indented further than that line and continue at the next line that is indented the same amount or less.
- After one block of an
ifstatement has run, skip its remainingelifandelsebranches. - Compare the output with what you expected. Repeat with further test cases until every block has run at least once.
Traps (5)
- Ask a true-or-false question
The usual slip is typing
=where you mean==. In the Shell,riders = 6gives the name a value and shows nothing.riders == 6asks the question and showsTrueorFalse. When a comparison shows nothing, count the equals signs.A quieter slip is comparing text with a number.
"6" == 6isFalse, and Python raises no error to warn you. If the value came frominput()and holds a whole number, make a number from it withintbefore you compare it with a number.The two-character operators have one spelling each. Write
>=,<=and!=with the=second.=>and=<are not Python operators. A file that holds one stops with a SyntaxError before its first line runs. - Choose a branch
A line with the wrong indentation can still be a legal program. Take an
ifstatement that has noelse, and suppose its block should display two lines. Leave the second at the margin and Python reports no error. It treats that line as the first line after theifstatement and runs it whatever the condition gave. Check the left edge of every line when a program does more than you expected.When an
else:follows, the same slip stops the program. A line at the margin ends theifstatement, so theelse:below it has noifto belong to, and Python reports a SyntaxError before any line runs.A missing colon is caught before the program starts.
if weight > 23with no colon stops with a SyntaxError before any line runs, and the message marks the place in that line where Python found the problem.Keep to four spaces for each level, and do not mix tabs with spaces. Start every statement of one block at the same depth. The blocks of statements nested inside it are indented further. A line whose depth fits no block stops the program with an IndentationError.
- Handle a boundary value
Writing
<where the rule needs<=moves one value to the wrong side. Withweight < 2, a parcel with a weight of2costs9coins. Every other whole-number weight is still priced correctly, so the mistake shows only in a test with 2.Using a second
ifwhere the rule needselifis the other common slip. Two separateifstatements are two separate decisions, and Python tests each one it reaches. Withif weight <= 2:followed byif weight <= 10:, a parcel with a weight of2passes both, and the second block replaces the price of4with9. Anelifis tested only when every condition above it in the same chain was false. - Combine two conditions
Each side of
andorormust be an expression that stands on its own. English lets you say "older than 12 and younger than 18". In Python,< 18is not an expression, soage > 12 and < 18stops with a SyntaxError. Writeage > 12 and age < 18.The slip that raises no error is
reply == "y" or "yes". Python reads it as(reply == "y") or "yes". The right side is the text "yes" on its own, and Python counts any text that is not empty as true. The condition therefore passes for every reply. Writereply == "y" or reply == "yes".When
andandorshare a line,andgroups more tightly.member or total > 50 and couponmeansmember or (total > 50 and coupon). If you mean the other grouping, write the parentheses. - Trace a ticket rule
Moving a line sideways can change which decision it belongs to, and Python accepts both versions. Suppose the whole
if member:statement is moved four spaces to the left, so that its first line starts at the margin. It no longer sits inside the outerelseblock, so Python reaches the test for every visitor, and every member gets the discount. A member aged 3 then gets 0 - 2, and the program displaysTicket: -2 coins. Trace one case for each branch after you change any indentation.A second slip is tracing only the case you had in mind when you wrote the code. The case you traced proves nothing about a visitor who takes a different branch. Check the list of test cases against the blocks, and add a case for any block that no test reaches.
Lesson 1 of 5
Ask a true-or-false question
Open this lessonLeans on 1Comes back in 0
Leans on
Comes back in
No lesson links recorded.
1 In plain words
A fairground ride has a height bar at its gate. A rider either reaches the bar or does not. The attendant never writes down how tall anyone is. The bar gives one of two answers, yes or no.
Python can ask the same kind of question about two values. Read 7 > 5 aloud as "is 7 greater than 5?" Python works the question out and gives back one of two values, True or False. These are the Boolean values, and their type is called bool. Write them with a capital first letter and no quotation marks.
An expression that asks such a question is a comparison. The symbol between its two sides is a comparison operator. This lesson uses six: < for less than, <= for less than or equal to, > for greater than, >= for greater than or equal to, == for equal to and != for not equal to.
A comparison of two numbers or two strings works out an answer and gives no name a new value. After riders > seats, both names hold what they held before. Giving a name a value is the job of an assignment, written with one =.
This lesson leans on two tools from the first unit. input() reads a line the user types and hands it back as text. int makes a whole number from text such as "6". A leading zero does not change the number: from "04" it makes 4, as the badge example in the first unit showed.
Remember one sentence: one = gives a name a value, and ==, written with two equals signs, asks whether two values are equal. To look the operators up, find the Comparisons section in the Built-in Types chapter of the Python 3.13 library reference.
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Boolean Type
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Comparisons
- Python Software Foundation, Python 3.13 Tutorial, 3.1.1 Numbers
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
2 Picture it
A table of four comparisons and their answers. 7 > 5 gives True. 7 < 5 gives False. 7 == 7 gives True. 7 != 7 gives False. The two rows that give True are marked.
3 Why
Python treats a comparison as a calculation. 7 + 5 works out to the number 12. 7 > 5 works out to the value True. The answer is a value like any other, so a program can print it or give it a name.
Arithmetic comes first. In riders == seats + 2, Python adds before it compares, so the question is asked about two finished values.
The single = already has a job, which is giving a name a value. The question of whether two values are equal has its own spelling, ==, and != asks the opposite question. For the whole numbers and strings in this lesson, != gives True exactly when == gives False.
4 The rule
A comparison has a value on each side of a comparison operator.
When both sides are numbers, or both are strings, Python works out the two sides, asks the question and gives back True or False. <, <=, > and >= ask about order. == asks whether the two values are equal, and != asks whether they differ.
Two whole numbers are equal when they are the same number. Two strings are equal when they hold the same characters in the same order, so "Gate" == "gate" is False. A string and a whole number are never equal, so "6" == 6 is False. Asking about order between a string and a number, as in "6" < 7, stops the program with a TypeError.
5 How
- Say the question in words. For the boat program below, one question is whether the number of riders is more than the number of seats.
- Choose the operator that matches the words. "More than" is
>. "At least" is>=. "Fewer than" is<. "At most" is<=. "Exactly" is==. "Anything but" is!=. - Check the types. A string and a whole number are never equal, so compare a number with a number and text with text. A value that came from
input()is text. When that text is a whole number such as6,intmakes a number from it, as the second worked example shows. - Work out each side to one value. Do any arithmetic first.
- Ask the question about those two values and write
TrueorFalse.
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Language Reference, 6.10 Comparisons
6 Worked example
Ask three questions about a boat
seats = 4
riders = 6
print(riders > seats)
print(riders == seats + 2)
print(riders != 6)
Standard input
Empty
Standard output
True
True
False
Predict each of the three output lines first. Then save the five lines as boat.py and run the file, or follow the trace below. Each comparison works out to True or False, and the addition in the fourth line is done before its comparison.
Compare a typed reply
reply = input()
print(reply == 6)
print(int(reply) == 6)
Standard input
6
Standard output
False
True
Save the three lines as reply.py, run the file, type 6 and press Enter. The first comparison sets the text "6" against the number 6, and a string never equals a whole number. The second makes a number from the reply first, so two numbers are compared.
Trace
| Instruction | Question in words | Result | Explanation |
|---|---|---|---|
seats = 4 | — | — | One = asks nothing. The name seats now holds 4. |
riders = 6 | — | — | The name riders now holds 6. |
print(riders > seats) | Is 6 greater than 4? | True | Six is greater than four, so Python displays True. |
print(riders == seats + 2) | Is 6 equal to 4 + 2? | True | Add first: 4 + 2 is 6. Then ask whether 6 equals 6. |
print(riders != 6) | Is 6 different from 6? | False | Six is not different from six, so Python displays False. |
7 The trap
The usual slip is typing = where you mean ==. In the Shell, riders = 6 gives the name a value and shows nothing. riders == 6 asks the question and shows True or False. When a comparison shows nothing, count the equals signs.
A quieter slip is comparing text with a number. "6" == 6 is False, and Python raises no error to warn you. If the value came from input() and holds a whole number, make a number from it with int before you compare it with a number.
The two-character operators have one spelling each. Write >=, <= and != with the = second. => and =< are not Python operators. A file that holds one stops with a SyntaxError before its first line runs.
- Python Software Foundation, Python 3.13 Tutorial, 3.1.1 Numbers
- Python Software Foundation, Python 3.13 Language Reference, 6.10 Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Tutorial, 8.1 Syntax Errors
Quick checks
Quick check 1 of 2
Predict the three lines this program displays. The program reads no input.
tickets = 12
group = 5
print(tickets >= group * 2)
print(tickets - 2 == group * 2)
print(tickets != 12)Show the steps and the answer
It displays True, then True, then False, each on its own line.
Why: Arithmetic comes first. 5 * 2 is 10, and 12 is at least 10. 12 - 2 is 10, which equals 10. The last line asks whether 12 differs from 12, and it does not.
Source: Python Software Foundation, Python 3.13 Language Reference, 6.10 Comparisons
Quick check 2 of 2
A program runs code = input() and the user types 08. Which of these three comparisons give True?
code == 8
code == "08"
int(code) == 8Show the steps and the answer
code == "08" and int(code) == 8 give True. code == 8 gives False.
Why: The reply is the text "08". Text equals text with the same characters, and text never equals a number. int turns "08" into the number 8, which equals 8.
Source: Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Comparisons
Sources
- Python 3.13 Library Reference, Built-in Types: Boolean Type. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Types: Comparisons. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 3.1.1 Numbers. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: input. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: int. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.10 Comparisons. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 8.1 Syntax Errors. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 2 of 5
Choose a branch
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
A footpath reaches a garden gate with a notice. If the gate is open, the notice says, cut through the garden. Otherwise, walk around the wall. You take one route, never both. Past the garden the two routes join and you carry on.
An if statement is that notice. Its first line holds the word if, then a condition, then a colon. A condition is an expression that Python judges to be true or false. In the worked programs of this unit every condition works out to True or False, like the comparisons from the last lesson. The lines to run when the condition is true go underneath, each one pushed in by four spaces more than the if line. A block inside that block goes four spaces further in, as the last lesson of this unit shows. Pushing a line in is called indenting it, and the indented lines together form a block.
A line else:, lined up with the if line, opens a second block. Python runs it when the condition is false. The else part is optional. Without it, a false condition makes Python skip the first block and do nothing in its place. Each route is called a branch.
A block ends at the first line that is indented less, or at the end of the file. When the whole if statement is done, Python carries on with the statement that follows it, whichever branch it took.
Remember one sentence: the colon opens a block, and the indentation says which lines belong to it. To look it up, see section 4.1 of the Python 3.13 tutorial, on if statements.
- Python Software Foundation, Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement
- Python Software Foundation, Python 3.13 Tutorial, 4.10 Intermezzo: Coding Style
- Python Software Foundation, Python 3.13 Tutorial, 4.1 if Statements
- Python Software Foundation, Python 3.13 Language Reference, 2.1.8 Indentation
2 Picture it
A table for the bag program with a column for the run where weight is 30 and a column for the run where weight is 18. On the if line the condition is True when weight is 30 and False when weight is 18. The if block runs in the first run and is skipped in the second. The else block is skipped in the first run and runs in the second. The last line runs in both.
3 Why
Python reads the indentation at the start of each line to decide which lines form a group. Lines indented by the same amount under an if line belong to its block. A line with less indentation is outside the block.
When Python reaches the if line, it works out the condition. If the condition is true, it runs the first block and passes over the else block. If the condition is false, it passes over the first block and runs the else block. Exactly one of the two runs.
The colon and the indentation work as a pair. The colon tells Python that a block follows. If the statement after the if line is not indented, Python finds no block and stops with an IndentationError before it runs any line of the file.
4 The rule
Write if, a condition and a colon.
Indent the block beneath it, by four spaces in this course. Python runs the block only when the condition is true. An optional else: line, lined up with the if, has its own indented block, which runs only when the condition is false. Lines after the whole statement, back at the left margin, run in both cases.
5 How
- Write the decision as two sentences, the first starting with if and the second with otherwise. The baggage rule invented for this lesson reads: if the bag is over the weight limit, charge a fee. Otherwise, charge nothing.
- Turn the first sentence into an
ifline. Writeif, then the condition, then a colon:if weight > 23:. - On the next lines, indented by four spaces, write what happens when the condition is True.
- If something different happens otherwise, write
else:lined up withif, and indent its lines by four spaces too. - Return to the left margin for the lines that run in both cases.
- Trace the program twice, once with a value that makes the condition True and once with a value that makes it False.
6 Worked example
Type 30 for a bag over the limit
reply = input()
weight = int(reply)
if weight > 23:
print("Heavy bag: pay the fee")
else:
print("No fee")
print("Next traveler")
Standard input
30
Standard output
Heavy bag: pay the fee
Next traveler
Save the code as bag.py, run it, type 30 and press Enter. The condition 30 > 23 is True, so the first block runs and the else block is skipped.
Type 18 for a bag under the limit
reply = input()
weight = int(reply)
if weight > 23:
print("Heavy bag: pay the fee")
else:
print("No fee")
print("Next traveler")
Standard input
18
Standard output
No fee
Next traveler
Run the same file and type 18. The condition 18 > 23 is False, so Python skips the first block and runs the else block. The last line runs in both cases.
Leave the block at the margin
weight = 30
if weight > 23:
print("Heavy bag: pay the fee")
Standard input
Empty
Standard output
Empty
Exception IndentationError
The print line is not indented, so the if line has no block. Python reports an IndentationError that names line 3 and displays nothing, because it found the problem before running line 1. Indent line 3 by four spaces to repair it.
Trace
| Instruction | What happens | Output | Explanation |
|---|---|---|---|
reply = input() | The user types 30 | — | The name reply holds the text "30". |
weight = int(reply) | weight is 30 | — | int turns the text into the number 30. |
if weight > 23: | 30 > 23 is True | — | The condition is True, so Python enters the first block. |
print("Heavy bag: pay the fee") | Runs | Heavy bag: pay the fee | This is the only line of the first block. |
else: | Skipped with its block | — | The first block ran, so the else block does not. |
print("Next traveler") | Runs | Next traveler | This line is back at the margin. It runs for every bag. |
7 The trap
A line with the wrong indentation can still be a legal program. Take an if statement that has no else, and suppose its block should display two lines. Leave the second at the margin and Python reports no error. It treats that line as the first line after the if statement and runs it whatever the condition gave. Check the left edge of every line when a program does more than you expected.
When an else: follows, the same slip stops the program. A line at the margin ends the if statement, so the else: below it has no if to belong to, and Python reports a SyntaxError before any line runs.
A missing colon is caught before the program starts. if weight > 23 with no colon stops with a SyntaxError before any line runs, and the message marks the place in that line where Python found the problem.
Keep to four spaces for each level, and do not mix tabs with spaces. Start every statement of one block at the same depth. The blocks of statements nested inside it are indented further. A line whose depth fits no block stops the program with an IndentationError.
- Python Software Foundation, Python 3.13 Language Reference, 2.1.8 Indentation
- Python Software Foundation, Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement
- Python Software Foundation, Python 3.13 Tutorial, 8.1 Syntax Errors
- Python Software Foundation, Python 3.13 Tutorial, 4.10 Intermezzo: Coding Style
- Python Software Foundation, Python 3.13 Library Reference, Built-in Exceptions: IndentationError
Quick checks
Quick check 1 of 2
This program has no else. What does it display? What would it display if the first line were stock = 9?
stock = 3
if stock < 5:
print("Order more")
print("Count done")Show the steps and the answer
With stock = 3 it displays Order more, then Count done. With stock = 9 it displays only Count done.
Why: 3 < 5 is True, so the block runs. 9 < 5 is False, and with no else Python skips the block and does nothing in its place. The last line is at the margin, so it runs both times.
Source: Python Software Foundation, Python 3.13 Tutorial, 4.1 if Statements
Quick check 2 of 2
What does this program display? Then suppose the line print("Keep the change") loses its four spaces and starts at the margin. What does the program display now?
coins = 2
if coins >= 5:
print("Buy a ticket")
print("Keep the change")
print("Walk home")Show the steps and the answer
As written it displays only Walk home. With that line at the margin it displays Keep the change, then Walk home.
Why: 2 >= 5 is False, so both indented lines are skipped. A line at the margin is outside the block, so it runs whatever the condition gave.
Source: Python Software Foundation, Python 3.13 Language Reference, 2.1.8 Indentation
Sources
- Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.10 Intermezzo: Coding Style. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.1 if Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 2.1.8 Indentation. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Exceptions: IndentationError. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 8.1 Syntax Errors. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 3 of 5
Handle a boundary value
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
Imagine a courier whose price depends on a parcel's weight. The rule is invented for this lesson, and the parcel program below follows it. A weight of 2 or less costs 4 coins. A weight above 2 and up to 10 costs 9 coins. Any heavier parcel costs 15 coins. Most weights sit well inside one price band. A weight of exactly 2 or exactly 10 sits where one price ends and the next begins. Python picks one of the three outcomes by asking conditions in order.
A value where a rule changes is a boundary value. < and <= give different answers only when the two sides are equal, so a wrong choice between them shows only at the boundary value.
A rule with three outcomes can be written with three branches. Python adds a branch with elif, which is short for "else if". An elif line comes after the if block, lined up with if, and carries its own condition and colon. An if statement can have several elif lines, and the else part stays optional.
Python asks the conditions from the top down and runs the block of the first one that is true. It skips every branch after that one, even if a later condition would also be true. If none is true, the else block runs, when there is one.
Remember one sentence: test each boundary value and the whole number on the other side of it. That advice is this lesson's own, and the lesson keeps to whole-number weights. To look up if, elif and else, see section 4.1 of the Python 3.13 tutorial.
2 Picture it
A table of four test weights. A weight of 2 passes the test weight <= 2 and costs 4. A weight of 3 first passes weight <= 10 and costs 9. A weight of 10 also first passes weight <= 10 and costs 9. A weight of 11 passes neither test and costs 15. The rows for the boundary values 2 and 10 are marked.
3 Why
Because the first true condition wins, each later condition is asked only about values the earlier ones turned away. In the parcel program, weight <= 10 is reached only when weight <= 2 was false. So on that line it means "more than 2 and at most 10" without saying the first half.
That shorter condition depends on the order. Put weight <= 10 first and every parcel with a weight of 2 or less passes it and is priced at 9 coins. Python reports no error, because both orders are legal programs. A test with a weight of 2 shows the wrong price.
The words of the rule choose the operator. "Up to 2" includes 2, so the test is <=. "Under 2" would leave 2 out, and the test would be <.
4 The rule
In an if, elif, else chain Python works out the conditions in order and runs the block of the first one that is true.
No later branch is tested or run. If every condition is false, the else block runs, and if there is no else, no block of the chain runs.
<= and >= include the value they are compared with. < and > leave it out.
5 How
- List the values where the rule changes. In the parcel rule they are 2 and 10.
- For each one, read the words of the rule and decide which side the value itself belongs to. The rule says up to 2, so 2 stays with the lighter parcels.
- Use
iffor the first band,eliffor each middle band andelsefor what is left. Put the conditions in order from one end of the range. The parcel program starts from the lowest cutoff. - Pick test values: each boundary value and the whole number on the other side of the change. The rule keeps 2 in the lower band, so the other side starts at 3. It keeps 10 in the middle band, so the other side starts at 11. The test values are 2, 3, 10 and 11.
- Work out the expected price for each test value by hand, from the words of the rule.
- Run or trace the program with each test value and compare. A mismatch at a boundary points to
<against<=or to the order of the conditions.
6 Worked example
Type 2, the first boundary value
reply = input()
weight = int(reply)
if weight <= 2:
price = 4
elif weight <= 10:
price = 9
else:
price = 15
print(price)
Standard input
2
Standard output
4
Save the code as parcel.py, run it and type 2. The first condition, 2 <= 2, is True, so the price is 4 and Python skips the other two branches.
Type 10, the second boundary value
reply = input()
weight = int(reply)
if weight <= 2:
price = 4
elif weight <= 10:
price = 9
else:
price = 15
print(price)
Standard input
10
Standard output
9
Run the file again and type 10. 10 <= 2 is False, so Python asks the elif condition. 10 <= 10 is True and the price is 9.
Type 11, the other side of the second boundary
reply = input()
weight = int(reply)
if weight <= 2:
price = 4
elif weight <= 10:
price = 9
else:
price = 15
print(price)
Standard input
11
Standard output
15
Run the file once more and type 11. Both conditions are False, so the else block sets the price to 15.
Trace
| weight | weight <= 2 | weight <= 10 | price | Explanation |
|---|---|---|---|---|
| 2 | True | not asked | 4 | The first condition is True, so Python never asks the second. |
| 3 | False | True | 9 | The other side of the first boundary. The elif branch runs. |
| 10 | False | True | 9 | The second boundary. <= keeps 10 in the middle band. |
| 11 | False | False | 15 | The other side of the second boundary. No condition is True, so else runs. |
7 The trap
Writing < where the rule needs <= moves one value to the wrong side. With weight < 2, a parcel with a weight of 2 costs 9 coins. Every other whole-number weight is still priced correctly, so the mistake shows only in a test with 2.
Using a second if where the rule needs elif is the other common slip. Two separate if statements are two separate decisions, and Python tests each one it reaches. With if weight <= 2: followed by if weight <= 10:, a parcel with a weight of 2 passes both, and the second block replaces the price of 4 with 9. An elif is tested only when every condition above it in the same chain was false.
Quick checks
Quick check 1 of 2
In a grading rule invented for this question, a score of 80 or more earns a merit, and a score of 50 or more earns a pass. What does this program display? Then name the two boundary values of the rule and, for each, the whole number on the other side of the change.
score = 50
if score >= 80:
print("merit")
elif score >= 50:
print("pass")
else:
print("retake")Show the steps and the answer
It displays pass. The boundary values are 50 and 80. The whole numbers on the other side are 49 and 79.
Why: 50 >= 80 is False and 50 >= 50 is True, so the elif block runs. The rule changes at 50 and at 80. "50 or more" keeps 50 with the passes, so the other side of that change is 49. "80 or more" keeps 80 with the merits, so the other side is 79.
Quick check 2 of 2
A sign invented for this question says "Children under 5 ride free." A program uses the condition age <= 5 for the free ride. Which single age shows the mistake, and what should the condition be?
Show the steps and the answer
Age 5 shows the mistake. The condition should be age < 5.
Why: "Under 5" leaves 5 out, but <= includes it, so a five-year-old rides free when the sign says to pay. age <= 5 and age < 5 agree for every other whole-number age.
Source: Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Comparisons
Sources
- Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Types: Comparisons. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.1 if Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 4 of 5
Combine two conditions
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
Here are two signs invented for this lesson. A sign at a ride says that you may board if you are tall enough and you hold a ticket. Height alone is not enough, and a ticket alone is not enough. A café sign offers a free refill if you are a member or you arrive early. There, one of the two is enough.
Python has three words for joining and flipping conditions. They are the Boolean operators and, or and not. In this unit each side of and or or is a whole condition of its own, such as height >= 120. A value that an operator works on is called an operand.
When each operand is True or False, the operators behave like the two signs. A and B is True only when both are True. A or B is True when at least one is True, and that includes the case where both are. not A flips one value, so True becomes False and False becomes True.
A condition can be given a name. has_ticket = ticket == "yes" looks odd at first. Read it with the rule for =: work out the right side, which is a comparison that gives True or False, then tie the name to that value.
Remember one sentence: and needs both, or needs one, not flips. To look them up, find the Boolean Operations section in the Built-in Types chapter of the Python 3.13 library reference.
2 Picture it
A truth table with one row for each pair of values of A and B. When A and B are both True, A and B is True and A or B is True. When A is True and B is False, A and B is False and A or B is True. When A is False and B is True, A and B is False and A or B is True. When both are False, A and B is False and A or B is False. The first and last rows are marked: A and B is True only in the first, and A or B is False only in the last.
3 Why
Python groups the parts of a condition in a fixed order. Arithmetic binds most tightly, then comparisons, then not, then and, and or last. So height >= 120 and has_ticket is read as (height >= 120) and has_ticket. Parentheses change the grouping, as they do in arithmetic.
Python works out the left side of and or or first, and it stops as soon as the answer is settled. With and, a false left side settles the answer, and Python does not work out the right side. With or, a true left side settles it.
In count != 0 and total / count > 5, Python works out the division only when count is not zero. When count is zero, the left side is False, and Python skips the right side.
4 The rule
When A and B are each True or False: A and B is True only if both are True.
A or B is True if at least one is True. not A is True if A is False, and False if A is True.
Without parentheses, comparisons group first, then not, then and, then or. Python works out the left side of and or or first, and works out the right side only when the left side has not settled the answer.
5 How
- Write the rule in words and underline each joining word: and, or, not.
- Write each part as a complete condition. A part is a comparison with its own left side, operator and right side, such as
height >= 120, or a name that already holdsTrueorFalse, such ashas_ticket. - Where the rule negates a part, write
notin front of that part, such asnot has_coat. - Join the parts with
andwhere both must hold and withorwhere one is enough. - If the rule mixes
andwithor, put parentheses around the part the rule treats as one group, as in(member or total > 50) and coupon. - Fill in a small table with one row for each case of the parts, True or False, and work out the whole condition for every row.
6 Worked example
Tall enough, with a ticket
height = int(input())
ticket = input()
has_ticket = ticket == "yes"
if height >= 120 and has_ticket:
print("Board the ride")
else:
print("Wait here")
Standard input
131
yes
Standard output
Board the ride
Save the code as ride.py, run it, type 131, press Enter, type yes and press Enter. The first line does two steps at once: input() hands back the typed text, and int makes a number from it. Both parts of the condition are True, so the whole condition is True.
Tall enough, without a ticket
height = int(input())
ticket = input()
has_ticket = ticket == "yes"
if height >= 120 and has_ticket:
print("Board the ride")
else:
print("Wait here")
Standard input
131
no
Standard output
Wait here
Run the file again and type 131, then no. The height part is True and the ticket part is False. and needs both, so the condition is False. A False condition sends Python to the else block.
Flip and join two named values
raining = True
has_coat = False
print(not raining)
print(raining and not has_coat)
print(raining or has_coat)
Standard input
Empty
Standard output
False
True
True
Save the five lines as rain.py. Predict the three output lines before you run the file. The middle line groups as raining and (not has_coat).
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: input
- Python Software Foundation, Python 3.13 Library Reference, Built-in Functions: int
- Python Software Foundation, Python 3.13 Language Reference, 6.11 Boolean operations
- Python Software Foundation, Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement
- Python Software Foundation, Python 3.13 Language Reference, 6.17 Operator precedence
Trace
| Instruction | Value | Output | Explanation |
|---|---|---|---|
height = int(input()) | 131 | — | The user types 131, and int turns the text into a number. |
ticket = input() | "no" | — | The user types no. The reply is text. |
has_ticket = ticket == "yes" | False | — | The right side asks whether "no" equals "yes". It does not, so has_ticket names False. |
height >= 120 | True | — | 131 is at least 120. |
height >= 120 and has_ticket | False | — | True and False gives False, because and needs both. |
print("Wait here") | — | Wait here | The condition is False, so the else block runs. |
7 The trap
Each side of and or or must be an expression that stands on its own. English lets you say "older than 12 and younger than 18". In Python, < 18 is not an expression, so age > 12 and < 18 stops with a SyntaxError. Write age > 12 and age < 18.
The slip that raises no error is reply == "y" or "yes". Python reads it as (reply == "y") or "yes". The right side is the text "yes" on its own, and Python counts any text that is not empty as true. The condition therefore passes for every reply. Write reply == "y" or reply == "yes".
When and and or share a line, and groups more tightly. member or total > 50 and coupon means member or (total > 50 and coupon). If you mean the other grouping, write the parentheses.
- Python Software Foundation, Python 3.13 Language Reference, 6.11 Boolean operations
- Python Software Foundation, Python 3.13 Language Reference, 6.10 Comparisons
- Python Software Foundation, Python 3.13 Library Reference, Built-in Types: Truth Value Testing
- Python Software Foundation, Python 3.13 Language Reference, 6.17 Operator precedence
Quick checks
Quick check 1 of 2
Predict the two lines this program displays. The program reads no input.
temp = 31
windy = False
print(temp > 30 and not windy)
print(temp < 0 or windy)Show the steps and the answer
It displays True, then False.
Why: 31 > 30 is True and not False is True, so and gives True. 31 < 0 is False and windy is False, and or needs at least one True.
Source: Python Software Foundation, Python 3.13 Language Reference, 6.11 Boolean operations
Quick check 2 of 2
What does each print line display?
member = True
total = 10
coupon = False
print(member or total > 50 and coupon)
print((member or total > 50) and coupon)Show the steps and the answer
The first line displays True and the second displays False.
Why: Without parentheses, and groups before or, so the first line means member or (total > 50 and coupon). member is True, so or gives True. In the second line the parentheses group member or total > 50, which is True, and True and False is False.
Source: Python Software Foundation, Python 3.13 Language Reference, 6.17 Operator precedence
Sources
- Python 3.13 Library Reference, Built-in Types: Boolean Operations. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.11 Boolean operations. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.17 Operator precedence. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: input. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Functions: int. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 6.10 Comparisons. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Library Reference, Built-in Types: Truth Value Testing. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
Lesson 5 of 5
Trace a ticket rule
Open this lessonLeans on 0Comes back in 0
Leans on
No lesson links recorded.
Comes back in
No lesson links recorded.
1 In plain words
Imagine a museum that prints its ticket rule on a board. The rule is invented for this lesson, and the museum program below follows it. Children under 5 enter free. Visitors under 16 pay 6 coins. Everyone else pays 10 coins. Members get 2 coins off any ticket that is not free. A clerk who reads the board for a member aged 16 goes down it line by line and lands on 8 coins. Python reads the program the same way, one condition after another.
The program for that board puts a decision inside a decision. An if statement written inside the block of another is called a nested if. In the museum program two nested if statements belong to the outer else block, so their if and else lines start four spaces in. The blocks of those nested statements start eight spaces in.
To trace a decision is to play the clerk. Write down the inputs, go through the lines in order, work out each condition you reach and note which block runs. A test case is one set of inputs together with the output you expect, worked out from the rule in words before you look at the code.
Remember one sentence: an else belongs to the if it lines up with. To look it up, see section 8 of the Python 3.13 language reference, on compound statements.
2 Picture it
A table of four test cases. Age 3, a member, pays 0. Age 15, not a member, pays 6. Age 16, not a member, pays 10. Age 16, a member, pays 8. The last row is marked: it is the case traced in this lesson.
3 Why
Indentation tells Python which lines belong to which block, and so which if each else answers. An else line pairs with the if line that starts at the same depth. In the museum program the first else is at the margin, so it pairs with if age < 5. The second else is four spaces in, so it pairs with if age < 16.
The outer decision runs first. Only when age < 5 is false does Python enter the outer else block and meet the two decisions inside it. For a child of 3, those inner lines are never reached, so the member discount cannot make a free ticket cost less than nothing.
A program with several branches needs several test cases. One run shows one path through the code. To see every block run at least once, choose inputs that send Python down each path.
4 The rule
A block may hold another if statement.
The inner statement's blocks are indented one level further, by four more spaces in this course. Python reaches the inner if only when the block that holds it runs. Each else or elif belongs to the if whose line starts at the same depth.
5 How
- Write the inputs for one test case at the top of a sheet, with the output you expect from the rule in words.
- Go down the program one line at a time. At an assignment, record the new value of the name.
- At an
iforelifline, work out the condition with the current values and write True or False beside it. - If it is True, move into the block beneath it. If it is False, skip every line indented further than that line and continue at the next line that is indented the same amount or less.
- After one block of an
ifstatement has run, skip its remainingelifandelsebranches. - Compare the output with what you expected. Repeat with further test cases until every block has run at least once.
6 Worked example
A member aged 16
age = int(input())
member = input() == "yes"
if age < 5:
price = 0
else:
if age < 16:
price = 6
else:
price = 10
if member:
price = price - 2
print(f"Ticket: {price} coins")
Standard input
16
yes
Standard output
Ticket: 8 coins
Save the code as museum.py, run it, type 16, press Enter, type yes and press Enter. The trace below follows this run. 16 < 5 is False, so Python runs the outer else block, where the price becomes 10 and the member discount brings it to 8.
A member aged 3
age = int(input())
member = input() == "yes"
if age < 5:
price = 0
else:
if age < 16:
price = 6
else:
price = 10
if member:
price = price - 2
print(f"Ticket: {price} coins")
Standard input
3
yes
Standard output
Ticket: 0 coins
Run the file again and type 3, then yes. 3 < 5 is True, so Python sets the price to 0 and skips the whole outer else block, including the member discount.
A visitor aged 15 who is not a member
age = int(input())
member = input() == "yes"
if age < 5:
price = 0
else:
if age < 16:
price = 6
else:
price = 10
if member:
price = price - 2
print(f"Ticket: {price} coins")
Standard input
15
no
Standard output
Ticket: 6 coins
Run the file once more and type 15, then no. The outer condition is False, the inner condition 15 < 16 is True, and member is False, so the price stays 6.
Trace
| Instruction | Condition | price | Explanation |
|---|---|---|---|
age = int(input()) | — | unset | The user types 16. age is the number 16. |
member = input() == "yes" | — | unset | The user types yes. The comparison gives True, so member names True. |
if age < 5: | 16 < 5 is False | unset | Skip the line indented under it and go to the else at the same depth. |
else: | — | unset | Enter the outer else block, where two more decisions wait. |
if age < 16: | 16 < 16 is False | unset | 16 is a boundary value. < leaves it out, so skip to the inner else. |
price = 10 | — | 10 | The inner else block runs, because the inner condition was False. |
if member: | member is True | 10 | A name that holds True or False can be a condition on its own. |
price = price - 2 | — | 8 | Work out 10 - 2 first, then give price the result. |
print(f"Ticket: {price} coins") | — | 8 | Back at the margin. The program displays Ticket: 8 coins. |
7 The trap
Moving a line sideways can change which decision it belongs to, and Python accepts both versions. Suppose the whole if member: statement is moved four spaces to the left, so that its first line starts at the margin. It no longer sits inside the outer else block, so Python reaches the test for every visitor, and every member gets the discount. A member aged 3 then gets 0 - 2, and the program displays Ticket: -2 coins. Trace one case for each branch after you change any indentation.
A second slip is tracing only the case you had in mind when you wrote the code. The case you traced proves nothing about a visitor who takes a different branch. Check the list of test cases against the blocks, and add a case for any block that no test reaches.
Quick checks
Quick check 1 of 2
Trace the museum program from the worked example for a visitor who types 5 and then no. What does it display, and which conditions did Python work out on the way?
Show the steps and the answer
It displays Ticket: 6 coins. Python worked out age < 5 as False, age < 16 as True and member as False.
Why: 5 is a boundary value, and < leaves it out, so the outer else block runs. 5 < 16 is True, which sets the price to 6. The reply no makes member False, so the discount block is skipped.
Quick check 2 of 2
Trace this program for the replies 40 and then yes. What does it display?
total = int(input())
express = input() == "yes"
if total >= 50:
cost = 0
else:
cost = 4
if express:
cost = cost + 3
print(cost)Show the steps and the answer
It displays 7.
Why: 40 >= 50 is False, so the else block runs and cost is 4. The nested if is inside that block, express is True, and 4 + 3 is 7.
Sources
- Python 3.13 Language Reference, 8 Compound statements and 8.1 The if statement. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Language Reference, 2.1.8 Indentation. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.10 Intermezzo: Coding Style. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.
- Python 3.13 Tutorial, 4.1 if Statements. Python Software Foundation. Python Software Foundation License Version 2. Read 1 Dec 2026.