
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
- Run the code and read the
AssertionError. What value tripped it? - Fix the formula. A
percentof25means 25 out of 100. - Add a second tripwire at the top of the function:
assert 0 <= percent <= 100with a helpful message.apply_discount(10, 150)must then raiseAssertionError. - Keep the first tripwire too.
- Run the code and read the
AssertionError. What value tripped it? - Fix the formula. A
percentof25means 25 out of 100. - Add a second tripwire at the top of the function:
assert 0 <= percent <= 100with a helpful message.apply_discount(10, 150)must then raiseAssertionError. - Keep the first tripwire too.
main.py Python sleeping
Press Run to try your code, then Check to test it.