In the last chapter, we saw how to intentionally raise an exception. Assertion is another way to raise an exception. Before understanding why we need assertion, let’s see how we can raise an exception using assertion.
Assertion is written using the assert
keyword. It is used to check a condition. If the condition is True, then it does nothing and the program execution continues normally. However, if the condition is False, then it throws the AssertionError
exception and the program gets terminated.
Let’s look at an example.
num = int(input("Enter a number"))
assert num > 0
print("The entered number is", num)
Here we wrote the assert statement as assert num > 0
. It checks if the condition num > 0 is True. If the condition is True, then nothing happens and the next statement is executed. Here we gave the input as 5, thus the condition num > 0 of the assert statement is True and so no exception was thrown.
Let’s see what would happen if we pass a negative number as input.
num = int(input("Enter a number"))
assert num > 0
print("The entered number is", num)
Here we gave the input as -5 which made the condition num > 0 of the assert statement False. Thus, the assert statement threw an AssertionError
exception.
The assert statement always throws the AssertionError
exception which is a built-in exception in Python.
Now that we know what assertion is, let’s discuss where it can be used.
Where is Assertion Used?
Assertions are mostly used for debugging or checking for any invalid values in a program. Normally, it is used for debugging and testing in large programs.
Let’s take a simplified example. Suppose you own a retail shop and want to get rid of all the products whose expiry date is less than 5 months. To do that, you can test whether the expiry date is greater than 5 months using assertion for each product and reject all the products for which the condition does not satisfy.
Consider another example in which you have a list of one thousand integer values. Now suppose your program is breaking because some values in the list might not be of type integer. In that case you can check the data type of those values using assertion in a loop.
In testing a software, we often use assert. Suppose, we have a list of test cases which should pass a particular function to ensure correct working of the program. In that case we use assert and if any of the test cases is not passed, then assert throws an error and we know that our program is not yet ready for production as it didn’t pass all test cases.
Now, you must have got an idea of where you can use assertions. So, let's move forward.
Using Assertion in Python
We have already seen an example in which assertion was used to check the validity of user input. Let’s look at one more example.
blood_group = ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-']
bgroup = input("Enter your blood group")
assert bgroup in blood_group
print("Your blood group is", bgroup)
The list blood_group
has the different types of blood groups as its elements. We are asking the user to enter the blood group. The condition of the assert statement bgroup in blood_group
checks if the value bgroup
entered by the user is present in the list blood_group
. If it is present, then the condition becomes True, but if not present, then the condition becomes False and the assert statement throws the AssertionError
.
We can also add a definition or error message to our raised AssertionError
by including the definition also in the assert statement as shown below.
blood_group = ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-']
bgroup = input("Enter your blood group")
assert bgroup in blood_group, "You entered an incorrect blood group!"
print("Your blood group is", bgroup)
In this example, we added the description of the exception in the assert statement by writing assert bgroup in blood_group, "You entered an incorrect blood group!"
, where bgroup in blood_group
is the condition to be checked and "You entered an incorrect blood group!" is the description or the error message. In the output, you can see the error message on giving an invalid input.
We can also handle the AssertionError using try and catch clauses like all other exceptions.
try:
roll = int(input("Enter your roll number"))
assert roll > 0, "You entered an incorrect Roll Number!"
except AssertionError as ex:
print(ex)
except:
print("Some error occurred.")
else:
print("You entered:", roll)
In this example, in the condition of the assert statement, we are checking if the roll number entered by the user is greater than 0. Let’s check the output for different input values.
If the user enters 5, then the condition of the assert statement becomes True and no exception is thrown. Therefore the statement written inside the else clause gets executed. We will get the following output.
You entered: 5
If the user enters -5, then the condition of the assert statement becomes False and the AssertionError exception is thrown. This exception gets handled by the first except clause. We will get the following output.
You entered an incorrect Roll Number!
If the user enters a string like “hello”, then the statement roll = int(input("Enter your roll number"))
throws the ValueError
exception which is handled by the second except clause and the output will be as follows.
Some error occurred.
Error handling becomes necessary when your program grows larger or more complex. Since the last few chapters, we learned about different types of errors and how to handle them. We also learned about the ways to raise new errors or create our own errors. So, start handling your errors elegantly.