Handle a boundary value — quick review
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.