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

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

-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

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 for | Raise an exception for |
|---|---|
| Internal assumptions (“this can’t be negative”) | User input and API data |
| Tests | File, network and payment problems |
| Debugging while developing | Anything 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

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:
- Print a stack trace in Python
- UnboundLocalError in Python
- If else in Python
- Check the type of a variable in Python
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.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn