Python assert statement

The assert statement is useful to check if a particular condition is fulfilled or not. The syntax is as follows:

CopiedCopy Code

assert expression, message 

In the above syntax, the 'message' is not compulsory.

If we want to assure that the user should enter only a number greater than 0, we can use assert statement as:

CopiedCopy Code

assert x>0, "Wrong input entered"  

In this case, the Python interpreter checks if x>0 is True or not. If it is True, then the next statements will execute, else it will display AssertionError along with the message "Wrong input entered".

assert examples:

CopiedCopy Code

x = int(input('Enter a number greater than 0:'))
assert x>0, "Wrong input entered" 
print('U entered: ',x)

The 'AssertionError ' shown in the above output is called an exception. An exception is an error that occurs during runtime. To avoid such type of exceptions, we can handle them using 'try ... except' statement. After 'try', we use 'assert' and after 'except', we write the exception name to be handled. In the except block, we write the statements that are executed in case of exception.:

A Python program to handle the AssertionError exception that is given by assert statement.

CopiedCopy Code

x = int(input('Enter a number greater than 0:'))
try: 
    assert(x>0) 
print('U entered: ',x) 
except AssertionError: 
print("Wrong input entered")