Python Assert Statement
The assert statement is useful to ensure that a given condition is True. If it is not true, it raises AssertionError. The syntax is as follows:
assert condition, message
If the condition is False, then the exception by the name AssertionError is raised along with the 'message' written in the assert statement. If 'message' is not given in the assert statement, and the condition is False, then also AssertionError is raised without message.
Assert Statement Example
A Python program using the assert statement and catching AssertionError. #handling AssertionError
try: x = int(input('Enter a number between 5 and 10:')) assert x>=5 and x<=10 print('The number entered:', x) except AssertionError: print('The condition is not fulfilled') A Python program to use the assert statement with a message. #handling AssertionError- try: x = int(input('Enter a number between 5 and 10:')) assert x>=5 and x<=10, "Your input is not correct" print('The number entered:', x) except AssertionError as obj: print(obj)