What is the assert for in Python?

March 29, 2022

What is the assert for in Python?

In this article you will learn what the assert is for in Python and what are the ways to use and get the most out of this statement.

What is the assert for in Python thumb

Hey programmer, how are you? Let’s learn more about Python!

The assert statement is used to verify the code, in a way that you can find bugs before putting your code into production.

That is, it guarantees that a condition for the code to continue its execution

Let’s see a practical example:

a = 5

assert a > 3

In this condition, the code will only proceed if a is greater than 3, which is true, so it runs all the code below without any problem.

But if we invert the sign:

a = 5

assert a < 3

We will get an AssertionError, which is where our code crashes, as technically it wouldn’t work if a is not less than 3

So this is the role of the assertion, guaranteeing the functionality of the code, doing value checks, type checks or whatever is necessary.

We can also say that the program will behave, as we are expecting.


A good reference for other assertion examples is this Python wiki

There you will see other points that the assert addresses


In this article we learned what the assert is for in Python

We can make checks throughout our code, checking some value, value type or whatever we need with the assert

So that the program runs the way we expect, thus managing to remove bugs in the development phase

Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x