Python assert Keyword



The Python assert keyword is a debugging tool, used to check the condition. If the given condition is True next line of the code is executed. If the given condition is False, it raises an AssertionError exception with an optional error message. It points out the error in the code.

Syntax

Following is the syntax of the Python assert keyword −

assert condition,error_message(optional)

Example

Following is an basic example of the Python assert keyword −

var = "hello"
#if condition returns True, then nothing happens:
assert var == "hello"
print("Code Execution Successful")

Output

Following is the output of the above code −

Code Execution Successful

Using 'assert' with False condition

When we pass the False condition along with assert it will raise an exception.

Example

In the following example, when we try to divide the with zero and the assert checked whether the divisor is zero or not as it is zero, it raised an exception −

# initializing number     
var1 = 4    
var2 = 0    
# It uses assert to check for 0     
print ("var1 / var2 value is : ")     
assert var2 != 0, "Divide by 0 error"    
print (var1 / var2)     

Output

Following is the output of the above code −

var1 / var2 value is : 
Traceback (most recent call last):
  File "/home/cg/root/91163/main.py", line 6, in 
    assert var2 != 0, "Divide by 0 error"    
AssertionError: Divide by 0 error
python_keywords.htm
Advertisements