Python’s assert keyword to check if a condition returns true or not. If it returns False, the execution of the program is to terminate and throw an AssertionError. And if the condition become True, then nothing happens.
Example 1-
Here, we have checked in division function that the denominator must be greater than 0. If the condition fails, python interpreter raises an AssertionError.
def division_fn(x,y): assert y > 0, 'y should be positive number' print("Division is :",x/y) division_fn(12,6) # condition become True, work perfectly fine division_fn(12,0) # condition become False, raise an AssertionError
# Output Division is : 2.0 # Output of division_fn(12,6) Traceback (most recent call last): # Output of division_fn(12,0) File "arg.py", line 6, in <module> divi_fn(12,0) File "arg.py", line 2, in divi_fn assert y > 0, 'y should be positive number' AssertionError: y should be positive number
Example 2 –
x = "apple" assert x == "banana", 'x should be apple'
# Output --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) <ipython-input-29-aea68b4ac1f5> in <module>() 1 x = "apple" ----> 2 assert x == "banana", 'x should be apple' AssertionError: x should be apple
. . .