Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

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 use assert to check user input. Use if + 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.

Search the guide