assertion

In Python, an assertion is a debugging aid that allows you to check that a condition is true at a particular point in your program. If the condition is true, execution continues. If it’s false, Python raises an AssertionError exception, which helps surface bugs and broken assumptions early.

Assertions are mainly intended for development and testing, because they can be globally disabled when Python runs in optimized mode, with the python -O command or by setting the PYTHONOPTIMIZE virtual environment. When optimized mode is enabled, Python ignores assert statements and any code guarded by __debug__.

The syntax is straightforward. Write assert <condition> and, optionally, add <message> to provide context if the assertion fails. The message becomes the argument to AssertionError.

Example

Here’s a quick example to illustrate how assertions work in Python:

Python
>>> def divide_numbers(x, y):
...     assert y != 0, "denominator should not be zero"
...     return x / y
...

>>> divide_numbers(10, 2)
5.0

>>> # This will raise an AssertionError
>>> divide_numbers(10, 0)
Traceback (most recent call last):
    ...
AssertionError: denominator should not be zero

In this example, divide_numbers() asserts that y isn’t zero. If you pass 0 as a value for y, then the assertion fails and Python raises AssertionError exception with the provided message.

Tutorial

Python's assert: Debug and Test Your Code Like a Pro

In this tutorial, you'll learn how to use Python's assert statement to document, debug, and test code in development. You'll learn how assertions might be disabled in production code, so you shouldn't use them to validate data. You'll also learn about a few common pitfalls of assertions in Python.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 8, 2026