Home »
Python
Python assert Keyword
By IncludeHelp Last updated : December 07, 2024
Description and Usage
The assert is a keyword (case-sensitive) in python, it is used to debug the code. Generally, it can be used to test a condition – if a condition returns False – it returns an Assertion Error (AssertionError).
Syntax
Syntax of assert keyword:
assert statement
Sample Input/Output
Input:
num = 10
# assert statement
assert num==20
Output:
assert num==20
AssertionError
Example 1
Test a False result
# python code to demonstrate example of
# assert statement
num = 10 # number
# assert statements
# nothing will happed as the condition is true
assert num==10
#AssertionError will generate as the condition is false
assert num==20
Output
Traceback (most recent call last):
File "/home/main.py", line 12, in <module>
assert num==20
AssertionError
Example 2
Test a False result and return a customize message
# python code to demonstrate example of
# assert statement
num = 10 # number
# assert statements
# nothing will happed as the condition is true
assert num==10
#AssertionError will generate as the condition is false
assert num==20, "There is an error with num's value"
Output
Traceback (most recent call last):
File "/home/main.py", line 12, in <module>
assert num==20, "There is an error with num's value"
AssertionError: There is an error with num's value