How to Use the Python assert Statement

09/17/2021

Contents

In this article, you will learn how to use the Python assert statement.

Python assert Statement

The assert statement in Python is used to assert that a certain condition is true. If the condition is false, then an AssertionError is raised with an optional error message. The assert statement is often used for debugging and testing purposes.

Syntax

The basic syntax of the assert statement is:

assert condition, error_message
Parameters
  • condition: The expression that you want to check.
  • error_message: An optional string message that will be displayed if the condition is false.
Example

Here are some examples of using the assert statement in Python:

Example 1:
x = 5
assert x == 5, "x should be 5"

In this example, the condition x == 5 is true, so the assert statement does nothing. If the condition was false, then an AssertionError would be raised with the message “x should be 5”.

Example 2:
y = 10
assert y > 20, "y should be greater than 20"

In this example, the condition y > 20 is false, so the assert statement raises an AssertionError with the message “y should be greater than 20”.

When you run your Python code with the -O (optimize) flag, all assert statements are ignored. This is useful in production environments where you don’t want to incur the performance cost of checking assertions.