Bug hunt

Tripwires

A bug often starts in one place but only causes trouble much later. By then, the clue is cold. An assert is a tripwire that catches it early:

assert condition, "message if it's False"

If the condition is True, nothing happens. If it's False, Python raises AssertionError with your message, right at that line.

def set_speed(knots):
    assert 0 <= knots <= 40, f"impossible {knots=}"
    ...

Use asserts for things that must be true if your code is correct. Don't use them to check what a user typed: Python can switch asserts off (with python -O). For user input, raise ValueError instead.

The bug report

apply_discount(price, percent) should take percent % off a price. apply_discount(80, 25) should give 60.0. Someone already set a tripwire on the result, and it's going off!

Assignment

  1. Run the code and read the AssertionError. What value tripped it?
  2. Fix the formula. A percent of 25 means 25 out of 100.
  3. Add a second tripwire at the top of the function: assert 0 <= percent <= 100 with a helpful message. apply_discount(10, 150) must then raise AssertionError.
  4. Keep the first tripwire too.