Decisions — quick review
Ask a true-or-false question
A fairground ride has a height bar at its gate.
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.
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.
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.
Choose a branch
A footpath reaches a garden gate with a notice.
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.
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.
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.
Handle a boundary value
Imagine a courier whose price depends on a parcel's weight.
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.
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.
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.
Combine two conditions
Here are two signs invented for this lesson.
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.
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.
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.
Trace a ticket rule
Imagine a museum that prints its ticket rule on a board.
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.
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.
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.