Python AssertionError – Tutorial with Examples

Python AssertionError - Tutorial with Examples

Debugging in Python is an essential process when it comes to developing code that is free from errors. Under the Python exception handling mechanism, the assert statement is used to raise an AssertionError when a condition that is to be True, fails. In this tutorial, we will be discussing the Python AssertionError and ways to handle it, with numerous examples that shall provide a clear understanding of the concept.

Syntax

The syntax to use the assert statement is as follows:

assert condition, error_message

Here, the condition is the logical check that is to be executed, and error_message is the message that would be displayed if the assertion fails. In case the condition is False, then an AssertionError is raised, with the message being displayed on the console.

Examples

Example 1: Simple Assertion

The below example demonstrates a simple assertion using the assert statement, where we check if the value of the variable a is equal to 10 or not.

a = 10
assert a == 10, "The value of 'a' should be 10"

The output of the above code block shall not return anything since the assertion is True. That means that the value of a which is 10, satisfies the condition.

Example 2: Assertion with a Function Call

Let us take another example where we shall check if the length of a list is less than a specified value or not. Here, we use a function call to calculate the length of the list.

def get_len(lst):
    return len(lst)

lst = [1, 2, 3]
assert get_len(lst) < 5, "The length of lst should be less than 5"

Here, the function get_len() is called that returns the length of the list lst. The assertion check is made, and if the length of the list is greater than or equal to 5, then an AssertionError is raised with the error message being displayed on the console.

Example 3: Handling Assertion Error

Let us consider a scenario where some input values are to be compared. If the values do not satisfy the condition, then an AssertionError would be raised. In such cases where there needs to be some action that needs to be performed, in case an AssertionError is raised, then we must handle them using the try-except block.

The below code block demonstrates the handling of AssertionError using the try-except block:

def get_avg(lst):
    if len(lst) > 0:
        return sum(lst) / len(lst)
    else:
        return None

lst = [1, 2, 3]
try:
    assert get_avg(lst) > 3, "The Average of the list should be greater than 3"
except AssertionError as e:
    print(f"Assertion Failed: {e}")

Here, we define the function get_avg(), which returns the average of the input list lst, provided it is non-empty. The assertion check is performed, to validate whether the average of the list is greater than 3 or not. In case the average value is less than 3, then an AssertionError shall be raised, which will be handled by the try-except block.

The output of the above code shall be:

Assertion Failed: The Average of the list should be greater than 3

Example 4: Assertion in a Loop

Let us take another example of using the assertion statement within a loop construct. Here, we shall define a list of integers, and we shall iterate over each element in the list. In each iteration, we shall use the assertion statement to check if the modulus of the number with 2 is zero or not. This shall determine whether the number is even or odd.

lst = [1, 2, 3, 4, 5]
for i in lst:
    assert i % 2 == 0 or i % 2 == 1, "The number is neither Even nor Odd"
    if i % 2 == 0:
        print(f"{i} is Even")
    else:
        print(f"{i} is Odd")

The output of the above code shall be:

AssertionError: The number is neither Even nor Odd

The AssertionError would be raised if any number in the list is neither even nor odd. However, here, we have passed such a list, where all numbers are either even or odd. Thus, the output shall display whether the number is even or odd.

Conclusion

The assert statement provides an efficient way to validate the code by testing the critical conditions in the code. In case of a failure, an AssertionError is raised, which marks that there is an error in the code that requires debugging. In this tutorial, we discussed the use of assertion statements, along with various examples that help visualize the practical use of this mechanism.

Leave a Reply

Your email address will not be published. Required fields are marked *