
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- What is the use of "assert" statement in Python?
- Assert Module in Node.js
- Global keyword in Python
- Finally keyword in Python
- Keyword arguments in Python
- How to compile assert in Java?
- Global keyword in Python program
- exit(), abort() and assert() in C/C++
- What is difference between Assert and Verify in Selenium?
- How to pass keyword parameters to a function in Python?
- How to assert that two Lists are equal with TestNG?
- How to check if a string is a valid keyword in Python?
- New keyword in Java
- This keyword in Java
- super keyword in Java

Advertisements