Assertion in Python with example
An Assertion is a basic check that can be turned on or off when the program is being tested. Using the assert statement, an expression is tested and if the result of the expression is False then an expression is raised. The assert statement is intended for debugging statements. It can be seen as an abbreviated notation for a conditional raise statement.
In Python, assertions are implemented using the
assert keyword. Assertions are usually placed at the start of a function to check for valid input and after a function call to check for valid output.
When Python encounters an assert statement, the expression associated with it is calculated and if the expression is False, an AssertionError is raised. It has the following Syntax:
assert expression[, arguments]
If the expression is False, Python uses ArgumentExpression as the argument for the AssertionError. It can be caught and handled like any other exception using a try-except block. However, if the AssertionError is not handled by the program, the program will be terminated and an error message will be displayed. In simple words, the assert statement is semantically equivalent to writing.
assert <expression>, <message>
The above statements mean that if the expression evaluates to False, an exception is raised and
Properties of Assertion:
1. Do not catch exceptions that you cannot handle.
2. User-defined exceptions can be very useful if some complex or specific information has to be stored in exception instances.
3. Do not create new exception classes when the built-in exceptions already have all the functionality you need.
c=int(input("Enter the temperature in Celsius:")) f=(c*9/5)+32 assert(f<=32), "It's freezing!" print("Temperature in Farenheit=", f)
Enter the temperature in Celsius:36 Traceback (most recent call last): File "C:/Users/Educlick/Documents/temperature.py", line 3, in <module> assert(f<=32), "It's freezing!" AssertionError: It's freezing!