Python assert With Examples

Hello everyone!! In this tutorial we will learn about python assert keyword. Python assert helps us to debug code. If you want to simulate your code like what is happening in which stage, then you can use python assert statements in your code. What is the expectation for the assignment of any variable can be detected using assert keyword in Python?

Python assert

The following is the basic structure of python assert statements:

You can also send information with the assert statement for the better understanding of the fault of the code.

Following is the way of giving a message with assert statement:

Python assert statement

Python assert statement takes a condition, the condition needs to be true. If the condition is true, that means the assertion of the value of the variable is ok, then the program will run smoothly and the next statements will be executed. But, if the condition is false ( that means there is some bug in our code) then it raises an exception.

Python assert example

We want to write a function that will return the quotient of two number. The following is the code:

If we run the above code then the output will be:

In the third line of the above code, you can see the assert statement. In this line, it is checked that whether the variable num2 value is greater than 0 or not. If greater than zero i.e. condition is true, then no problem occurs and we get the output accordingly.

But when we called the function division() with the 2nd argument 0, then the assert condition is false. That is why a AssertionError occurs and it gives the message “Divisor cannot be zero”, that we wrote in the message part of the python assert statement. Read more about python exception handling.

Python assert example with variable replacement

Consider the following code, we are trying to find square root of the equation say (b2 - 4ac).

Output will be:

Python assert

This is how we can use python assert statements to debug and find the bugs in our code in the testing phase. You can learn more about testing code using unitest module.

By admin

Leave a Reply