assert keyword in Python


Every programming language has feature to handle the exception that is raised during program execution. In python the keyword assert is used to catch an error and prompt a user defined error message rather than a system generated error message. This makes it easy for the programmer to locate and fix the error when it occurs.

With Assert

In the below example we use the assert key word to catch the division by zero error. The message is written as per the wish of the programmer.

Example

 Live Demo

x = 4
y = 0
assert y != 0, "if you divide by 0 it gives error"
print("Given values are ","x:",x ,"y:",y)
print("\nmultiplication of x and y is",x * y)
print("\ndivision of x and y is",x / y)

Running the above code gives us the following result:

Traceback (most recent call last):
File "scratch.py", line 3, in
assert y != 0, "if you divide by 0 it gives error"
AssertionError: if you divide by 0 it gives error

Without Assert

Without the assert statement we get the system generated errors which may need further investigation to understand and locate the source of the error.

Example

 Live Demo

x = 4
y = 0
#assert y != 0, "if you divide by 0 it gives error"
print("Given values are ","x:",x ,"y:",y)
print("\nmultiplication of x and y is",x * y)
print("\ndivision of x and y is",x / y)

Running the above code gives us the following result:

multiplication of x and y is 0
Traceback (most recent call last):
File "scratch.py", line 6, in <module>
print("\ndivision of x and y is",x / y)
ZeroDivisionError: division by zero

Updated on: 02-Jan-2020

122 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements