
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
Advertisements