What Does assert Do in Python? (With Examples)

What does assert do in Python? It checks a condition and raises AssertionError if the condition is false; if it’s true, nothing happens. You can add a message after a comma:

assert total >= 0, "total can't be negative"

I ran these checks on Python 3.12.5, including the same script with assertions switched off.

We’ll trigger an AssertionError, see why python -O skips asserts, avoid the parentheses mistake, compare assert with raising errors, and use assert in pytest.

How assert works

Use assert for things that should never happen if your code is correct. Here a checkout function asserts the discounted price makes sense:

def apply_discount(price, percent):
    discounted = round(price * (1 - percent / 100), 2)
    assert 0 <= discounted <= price, f"bad discount: {percent}% turned ${price} into ${discounted}"
    return discounted

print(apply_discount(80.00, 25))
print(apply_discount(80.00, 150))       # a bug upstream sent 150%

Output:

60.0
Traceback (most recent call last):
  File "C:\pyguides\checkout.py", line 7, in <module>
    print(apply_discount(80.00, 150))       # a bug upstream sent 150%
          ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\pyguides\checkout.py", line 3, in apply_discount
    assert 0 <= discounted <= price, f"bad discount: {percent}% turned ${price} into ${discounted}"
           ^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: bad discount: 150% turned $80.0 into $-40.0
Command Prompt output of a Python assert statement passing once and then raising AssertionError with a custom message
The 25% discount passed; the 150% one stopped the program with a clear message.

The message is evaluated only when the assertion fails, so an f-string there costs nothing in normal runs. Without a message, you just get a bare AssertionError.

Why python -O ignores assert statements

Running Python with -O (optimize) removes every assert, and the program carries on with the bad value:

python -O checkout.py

Output:

60.0
-40.0
Command Prompt output of the same Python script under python -O where the assert is skipped and a negative price is returned
With -O, the broken discount slipped through as a negative price.

That’s exactly why asserts must never be your only defense for user input, payments or security checks: someone can turn them off.

The parentheses mistake

assert is a statement, not a function. Wrapping the condition and message in parentheses creates a tuple, and a non-empty tuple is always true:

cart_total = -5.00

assert(cart_total >= 0, "total can't be negative")     # WRONG: this is a non-empty tuple
print("tuple version passed?!")

assert cart_total >= 0, "total can't be negative"      # right

Output:

C:\pyguides\assert_tuple.py:3: SyntaxWarning: assertion is always true, perhaps remove parentheses?
  assert(cart_total >= 0, "total can't be negative")     # WRONG: this is a non-empty tuple
tuple version passed?!
Traceback (most recent call last):
  File "C:\pyguides\assert_tuple.py", line 6, in <module>
    assert cart_total >= 0, "total can't be negative"      # right
           ^^^^^^^^^^^^^^^
AssertionError: total can't be negative
Command Prompt output of Python warning that an assertion with a tuple is always true, then the correct assert raising AssertionError
Python warns about it, the tuple version passes silently, and the correct one fails as it should.

assert vs raising an exception

For checks on input you don’t control, raise a real exception instead. It can’t be disabled, and callers can catch it. See types of errors in Python:

def set_quantity(qty):
    if not isinstance(qty, int) or qty < 1:
        raise ValueError(f"quantity must be a positive whole number, got {qty!r}")
    return qty

for value in [3, 0, "2"]:
    try:
        print("ok:", set_quantity(value))
    except ValueError as err:
        print("ValueError:", err)

Output:

ok: 3
ValueError: quantity must be a positive whole number, got 0
ValueError: quantity must be a positive whole number, got '2'
Use assert forRaise an exception for
Internal assumptions (“this can’t be negative”)User input and API data
TestsFile, network and payment problems
Debugging while developingAnything that must run in production

assert in pytest

pytest uses plain assert statements and rewrites them to show exactly what differed when a test fails:

def order_total(prices, tax_rate=0.0825):
    return round(sum(prices) * (1 + tax_rate), 2)

def test_order_total():
    assert order_total([19.99, 5.25]) == 27.32

def test_order_items():
    order = {"items": ["coffee", "bagel"], "state": "TX"}
    assert order == {"items": ["coffee", "muffin"], "state": "TX"}
python -m pytest -q test_orders.py

Output:

.F                                                                       [100%]
================================== FAILURES ===================================
______________________________ test_order_items _______________________________

    def test_order_items():
        order = {"items": ["coffee", "bagel"], "state": "TX"}
>       assert order == {"items": ["coffee", "muffin"], "state": "TX"}
E       AssertionError: assert {'items': ['c...'state': 'TX'} == {'items': ['c...'state': 'TX'}
E         
E         Omitting 1 identical items, use -vv to show
E         Differing items:
E         {'items': ['coffee', 'bagel']} != {'items': ['coffee', 'muffin']}
E         Use -v to get more diff

test_orders.py:9: AssertionError
=========================== short test summary info ===========================
FAILED test_orders.py::test_order_items - AssertionError: assert {'items': ['...
1 failed, 1 passed in 0.06s
Command Prompt output of pytest with one passing test and one failing assert showing the differing dictionary items
One test passed; for the failing one, pytest pointed straight at the differing items: bagel vs muffin.

The total test passed because $25.24 plus 8.25% tax really is $27.32. Outside pytest, the same bare assert would just say AssertionError with no details. For running doc examples as tests instead, see what is a docstring in Python.

More guides on errors and debugging:

Frequently asked questions

What does assert do in Python?

It tests a condition and raises AssertionError if it’s false. If the condition is true, the program continues.

How do I add a message to assert?

Put it after a comma: assert x > 0, "x must be positive".

Why is my assert always passing?

You probably wrapped it in parentheses, assert(cond, "msg"), which makes an always-true tuple. Remove the parentheses.

Should I use assert for input validation?

No. Asserts disappear under python -O. Raise ValueError or TypeError instead.

Is assert used in testing?

Yes. pytest is built around plain assert statements and shows detailed failure output.

Where is the assert statement documented?

See The assert statement in the Python docs.