Skip to content

What is assert in Python

Learn what the assert statement is and its usage in Python.

Assert statement in python is a way to check for unrecoverable conditions before proceeding further in a program. It prevents runtime errors by evaluating causes that could certainly raise an error after performing a few operations. It is similar to a self-checking mechanism for a program, a bug-free program should not be affected by asserts. An assert is equivalent to:

if not condition:
    raise AssertionError("my-message")

When a python program is run in an optimized mode (where __debug__ is False), as shown below, assert is ignored.

python -O

The assert statement needs an expression to evaluate and an optional message, the expression should result in a Boolean value, True or False. If the result is False an AssertionError is raised with provided message.


assert <expression> [, "message"]

Following are a few sample usages of assert

Check if a number is even

assert num % 2 == 0, "Number is not even"

Checking for membership in a list

assert 2 in [1, 3, 4], "2 is not in the list"

Leap year detection

assert (year % 400 == 0 and year % 100 == 0) or (year % 4 ==0 and year % 100 != 0), f"{year} is not a leap year"

Usage in a function

def apply_discount(price: float, discount: float) -> float:
    assert 0 <= discount <= 100 # discount is in percentage
    discounted_price = price - (price * discount / 100)
    return discounted_price

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*

PySaaS: The Pure Python SaaS Starter Kit

🚀 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏