In this tutorial we will discuss assertion in python, and how we can use the assert keyword to perform assertion.
Assertion is a special statement we use in python, and it is similar to the if statement. Like an, if statement assertion statement works on boolean data types and shows result according to the True and False values.
We do not often use assertion statements in our program, it only used when we are completely sure about the boolean statement. For example, if we want user to enter only 1, the program will further execute if the user enters 1 else the program crash and throw an error, so for this here we can use the assertion statement.
Like the conditional statements, the assertion statement works on boolean values (True and False), and the execution of the next lines depend upon the True boolean value. The only difference between the conditional statement and the assertion statement, the assertion statement throws an error if the boolean value is False.
We typically use the assertion statement as a debugging tool to check the False values, it stops the execution of the program where it finds the False value.
In python, we have a keyword assert which can be used to create the assertion statement. The execution of the next code depends on the assertion conditional or boolean value if the value is True the next line of code executes else it throws an error.
assert <condition> , <optional error message>
The syntax to write an assert statement is very easy, the only thing we require is the assert keyword and a condition which returns a boolean value. The <optional error message> is completely optional, it is used to provide some additional information about the error.
Here in this example, we will write a program which asks the user to enter his age for registration and we only register those users which age lay between 18 to 30 (include). If the user age is not between 18 to 30 then we will not accept the user registration and throw an Assertion error.
name = input("Enter your name: ") age = int(input("Enter your age: ")) assert (age >= 18) and (age <= 30) , "Your age is not between 18 to 30" print("You are registered")
Output: (without Error)
Enter your name: Sam 25 Enter your age: 25 You are registered
Enter your name: Juli Enter your age: 34 assert (age >= 18) and (age <= 30) , "Your age is not between 18 to 30" AssertionError: Your age is not between 18 to 30
Behind the code:
In the above code, we have asked the user to enter his name and age, and the assert statement working on a condition where it is checking whether the age enters satisfy a specific condition or not. If the user enters age between 18 to 30 the print(“You are registered”) statement executes else the AssertionError raise.
Points to Remember:
- The assertion statement is similar to the conditional statement.
- To create an assertion statement, we use assert keyword
- If the condition is False it throws an AssertionError
- It is typically used for debugging