Quarry School

Decisions: crash course

about 9 min to listen5 lessons0 questions to tryUnit 3 of 6

Short view. Each lesson's rule, its steps and its trap. Switch to Full for a worked example and a question to try in every lesson.Full view. Each lesson's rule, its steps, one worked example with Watch it solved, the trap, and one question to try.

Starts here no skill from another unit needed first

1 Ask a true-or-false question

about 2 minOpen the full lessonOnly this lesson

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.

How

  1. 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.
  2. Choose the operator that matches the words. "More than" is >. "At least" is >=. "Fewer than" is <. "At most" is <=. "Exactly" is ==. "Anything but" is !=.
  3. 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 as 6, int makes a number from it, as the second worked example shows.
  4. Work out each side to one value. Do any arithmetic first.
  5. Ask the question about those two values and write True or False.

Worked example

Ask three questions about a boat

Python code
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

Python code
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.

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.

2 Choose a branch

about 2 minOpen the full lessonOnly this lesson

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.

How

  1. 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.
  2. Turn the first sentence into an if line. Write if, then the condition, then a colon: if weight > 23:.
  3. On the next lines, indented by four spaces, write what happens when the condition is True.
  4. If something different happens otherwise, write else: lined up with if, and indent its lines by four spaces too.
  5. Return to the left margin for the lines that run in both cases.
  6. Trace the program twice, once with a value that makes the condition True and once with a value that makes it False.

Worked example

Type 30 for a bag over the limit

Python code
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

Python code
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

Python code
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.

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.

3 Handle a boundary value

about 2 minOpen the full lessonOnly this lesson

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.

How

  1. List the values where the rule changes. In the parcel rule they are 2 and 10.
  2. 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.
  3. Use if for the first band, elif for each middle band and else for what is left. Put the conditions in order from one end of the range. The parcel program starts from the lowest cutoff.
  4. 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.
  5. Work out the expected price for each test value by hand, from the words of the rule.
  6. 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.

Worked example

Type 2, the first boundary value

Python code
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

Python code
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

Python code
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.

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.

4 Combine two conditions

about 2 minOpen the full lessonOnly this lesson

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.

How

  1. Write the rule in words and underline each joining word: and, or, not.
  2. 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 holds True or False, such as has_ticket.
  3. Where the rule negates a part, write not in front of that part, such as not has_coat.
  4. Join the parts with and where both must hold and with or where one is enough.
  5. If the rule mixes and with or, put parentheses around the part the rule treats as one group, as in (member or total > 50) and coupon.
  6. 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.

Worked example

Tall enough, with a ticket

Python code
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

Python code
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

Python code
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).

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.

5 Trace a ticket rule

about 1 minOpen the full lessonOnly this lesson

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.

How

  1. Write the inputs for one test case at the top of a sheet, with the output you expect from the rule in words.
  2. Go down the program one line at a time. At an assignment, record the new value of the name.
  3. At an if or elif line, work out the condition with the current values and write True or False beside it.
  4. 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.
  5. After one block of an if statement has run, skip its remaining elif and else branches.
  6. Compare the output with what you expected. Repeat with further test cases until every block has run at least once.

Worked example

A member aged 16

Python code
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

Python code
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

Python code
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.

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.