Skip to main content

How to Use the assert Statement in Python

Implementing the assert statement in Python is straightforward: We use assert to test conditions and display a message if the condition is false.
May 2024  · 6 min read

The assert statement in Python programming is a tool for establishing fundamental truths in your code. They work by empowering developers to validate assumptions within their code. In this tutorial, we will master Python's assert statement, including its syntax, usage, and applications in debugging and error detection. By mastering Python's assert statement, we will be one step closer to becoming an expert Python Programmer

The Short Answer: How to Write Python Assertions 

The syntax of the assert statement is straightforward:

assert condition, message

Here, condition refers to the expression being tested, while message is an optional error message that appears if the assertion fails.

Here are a few assertions you can try in your Python code to get the hang of it. In the first case, the expression 3<4>5 is logically incorrect so Python raises an AssertionError with the message that we provided: "Math does not work that way." In the second case, the expression 0==0 is a tautology so we never see the message, "This shouldn't throw an error." 

assert 3<4>5, "Math does not work that way."
assert 0==0, "This shouldn't throw an error."

Overview of Python's assert Statement

Let's now take a closer look into Python's assert statement, including how and why it is used. By the end of this tutorial, you will be an expert in how to use the assert statement in Python. 

What are Python assertions?

Assertions in programming, more generally, are constructs used to verify the veracity of conditions in the codebase. In other words, they are truths that the program must comply with, or else they will throw an error. By using the word "assert", Python implements these programming assertions with very literal syntax: The assert statement allows us to create these assertions.

When to use Python assertions

Assertions are invaluable for debugging, validating assumptions, and ensuring your code behaves as expected under specific conditions. They allow you to tell the computer what you expect it to do and ask it to stop when it’s doing something differently. This is useful when building a new program or adding a feature or updating an existing app.

Assertions shine in scenarios where developers must enforce preconditions, postconditions, or invariants within their codebase. They act as guardrails, preventing the code from progressing if certain conditions are violated, thus aiding in the early detection of potential bugs.

By strategically placing assertions throughout the code, you can catch errors closer to their origin, simplifying debugging. DataCamp's Python Developer career track is a great course for aspiring developers of all levels to practice functional programming skills because it includes exercises with both basic and more advanced concepts.

When not to use Python assertions

While assertions are invaluable during development, there are scenarios where their usage might be inappropriate.

It’s important to understand that when your code gets compiled for production, the assertions may be globally disabled. This means you should not rely on assertions to handle run-time problems, like a user inputting the wrong data. Instead, they should be used for development problems, like identifying logic or math inaccuracies.

For handling errors or validating data in production code, try incorporating exception handling constructs to allow the code to gracefully recover from errors, log relevant information for debugging purposes, and provide meaningful feedback to users.

You can learn more about finding errors and correcting them in our Exception and Error Handling in Python tutorial or by taking our Associate Data Scientist in Python course. 

Common Mistakes and Misconceptions with the assert Statement in Python

A common mistake when using the assert statement in Python is to use parentheses. This is an understandable mistake since many functions use parentheses, and including them can feel like second nature. However, the assert statement is not technically a function in Python so it uses a special syntax. If you use parentheses, you will likely run into syntax warnings and logical errors.

Example of an error due to parentheses being used in an assert statement.SyntaxWarning: assertion is always true, perhaps remove parentheses?

Another common mistake is forgetting the comma after the condition. Doing so will result in a syntax error.

Example of an error due to a missing comma in an assert statement.SyntaxError: invalid syntax

The AssertionError exception

An AssertionError exception is raised whenever the terms of an assertion are violated. This error halts program execution; any optional error message you set will be displayed. Given that assertions are used primarily to test your code during development, if you get a Python AssertionError exception message, you generally want to take it seriously. It could point to a fatal flaw in your code.

Practical Applications

An assert statement can be used in many practical applications in Python. Our Writing Functions in Python interactive course provides many exercises that will help you gain mastery. Here are a couple of examples. 

Using assert within a function

A useful way to use assertions is to insert them into functions. This can help ensure that your functions behave as intended.

def divide(a, b):
assert b != 0, "Division by zero!"
return a / b

# Test cases
print(divide(10, 2))  # Output: 5.0
print(divide(8, 0))   # AssertionError: Division by zero!

Using assert with unittest

Testing your code is an essential step in the development process. Unittest is a library designed to help you test your code efficiently, and it utilizes assert statements to do so. This is the most often way I use assert statements. Here’s an example that you might find in our Introduction to Testing in Python course. 

import unittest

class TestMathFunctions(unittest.TestCase):
    def test_addition(self):
        self.assertEqual(2 + 2, 4)

    def test_subtraction(self):
        self.assertEqual(5 - 3, 2)

    def test_division(self):
        self.assertRaises(ZeroDivisionError, divide, 10, 0)

if __name__ == '__main__':


Python's assert statement is a vital tool for debugging and verifying conditions in your code during development. While simple and effective for testing assumptions, it should not be relied upon in production due to its deactivation in compiled code. Instead, exception handling should be used for robust error management. 

Consider our reading our Coding Best Practices and Guidelines tutorial as a resource for lingering questions.

Photo of Amberle McKee
Amberle McKee

I am a PhD with 13 years of experience working with data in a biological research environment. I create software in several programming languages including Python, MATLAB, and R. I am passionate about sharing my love of learning with the world.


Learn with DataCamp


Writing Efficient Python Code

4 hr
Learn to write efficient code that executes quickly and allocates resources skillfully to avoid unnecessary overhead.
See DetailsRight Arrow
Start Course
See MoreRight Arrow


Unit Testing in Python Tutorial

Learn what unit testing is, why its important, and how you can implement it with the help of Python.
Abid Ali Awan's photo

Abid Ali Awan

10 min


Exception & Error Handling in Python

Errors and exceptions can lead to program failure or unexpected behavior, and Python comes with a robust set of tools to improve the stability of the code.
Abid Ali Awan's photo

Abid Ali Awan

21 min


Python IF, ELIF, and ELSE Statements

In this tutorial, you will learn exclusively about Python if else statements.
Sejal Jaiswal's photo

Sejal Jaiswal

9 min


How to Use Pytest for Unit Testing

Explore what Pytest is and what it's used for while comparing it to other software testing methods.
Kurtis Pykes 's photo

Kurtis Pykes

17 min


Python Logical Operators: A Hands-on Introduction

Python offers three logical operators: and, or, and not. These operators, also known as Boolean operators, evaluate multiple conditions and determine an expression's overall truth value.
Stephen Gruppetta's photo

Stephen Gruppetta

17 min


Python Tutorial for Beginners

Get a step-by-step guide on how to install Python and use it for basic data science functions.
Matthew Przybyla's photo

Matthew Przybyla

12 min

See MoreSee More