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?
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:
assert condition, your message
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:
# defining the function definition def divide(num1, num2): assert num2 > 0 , "Divisor cannot be zero" return num1/num2 # calling the divide function a1 = divide(12,3) # print the quotient print(a1) # this will give the assertion error a2 = divide(12,0) print(a2)
If we run the above code then the output will be:
4.0 Traceback (most recent call last): File "D:/T_Code/PythonPackage3/Assert.py", line 10, in a2 = divide(12,0) File "D:/T_Code/PythonPackage3/Assert.py", line 3, in divide assert num2>0 , "Divisor cannot be zero" AssertionError: Divisor cannot be zero
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).
import math def sqrt(a,b,c): assert b*b >= 4*a*c, "Cannot find square root of negative number, found %s < %s" % (b*b, 4*a*c) return math.sqrt(b*b - 4*a*c) print(sqrt(10, 12, 3)) # this will cause assertion error print(sqrt(-4, 5, -3))
Output will be:
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.