──────────────────────────────────────

43. Build Your Own Python Program · Repair a Rule and Retest It

Find a decision error by testing a function on either side of its limit.

Lesson files · lessons/build-your-own-program/repair-and-retest

Before you start
- Write a function with parameters and a return value.
- Use assert to check a prediction about code.
- Compare whole numbers with < and <=.

By the end
- Use an exact-limit test to find a comparison bug.
- Fix the comparison and show that cases on both sides still pass.

Where you can use it
Repair a stock alert or eligibility rule and keep its successful cases working.

Run the smallest test that shows the problem. If a battery warning should turn on only below 20 percent, try 19, 20 and 21. The value 20 tells you whether the comparison includes the boundary.

Keep the comparison in its own function. You can call it with made-up numbers and test one precise result without starting the whole program. After the fix, rerun the original failing test and the two nearby checks.

Predict
Which input best distinguishes < 20 from <= 20?
- 20
- 19

Worked example (example.py)

def low_battery(charge, warning_level):
    return charge < warning_level

assert low_battery(19, 20) is True
assert low_battery(20, 20) is False
print("Battery checks passed")


Example result
Battery checks passed

Repair the supply alert from the starter. A shelf is Ready when the number of items is at or above its target. Read the number of items, then the target. Print Ready or Restock. Use an assertion for a shelf that has exactly enough items.

Starter program (starter.py)

def needs_more(items, target):
    return items <= target

items = int(input())
target = int(input())
if needs_more(items, target):
    print("Restock")
else:
    print("Ready")


Starter input
8
8

Hint
Reproduce the failure with eight items and a target of eight. Find the comparison in needs_more().

Case 1. Try the sample
Input
8
8
Expected output
Ready

Case 2. One item short
Input
7
8
Expected output
Restock

Case 3. Above the target
Input
9
8
Expected output
Ready

Stretch
Show the test that would catch an accidental change from < to >.

Reflect
Explain which single case showed the original error and why.

Check your prediction
20 Both comparisons accept 19. They make different decisions about 20.
