Part 11 / Topic 3 of 12
assert and its limits
assert condition, "message" does nothing if the condition is True. If it is False, it raises AssertionError with your message.
Like a quick "is the oven hot?" check before you bake.
price, qty = 20, 10
assert price * qty == 200, "10 pens should cost 200" # passes, nothing happens
try:
assert price * qty == 250, "10 pens should cost 250"
except AssertionError as error:
print("AssertionError:", error) # AssertionError: 10 pens should cost 250
Limits of plain assert in a script:
- The first failure stops everything. You never learn if the other checks pass.
- No summary of what passed and what failed.
python -O(optimise mode) switches all asserts off, so never useassertto check user input. Useif+raise ValueError(...)instead (Part 6).
pytest fixes the first two problems: it runs every test, even after a failure, and gives a clear report. Demo: 03_assert_basics.py.
Done here? The practice set for Part 11 — 7 exercises with solutions — is on the part page.