Python

Python AssertionError

Python users or programmers use the “assert” statement to define a condition that must be true. If the condition is satisfied/true, the code proceeds to the next line. But if the condition is false, the program stops running/executing and displays an error message. This concept is called “assertion”.

This guide will show you how to use Python AssertionError with many examples. It will explain the below/following topics:

What is the AssertionError in Python?

The AssertionError in Python is a powerful exception that is triggered when the assert statement fails. This statement is an in-built feature of Python that is used to test a condition and raise/throw an exception/error if the condition is not satisfied.

AssertionError Working in Python

Python has a feature called “assert statement” that helps us find errors in our code. If the statement is false, Python will return an “AssertionError”. This error belongs to the “Exception” class, which is according to the “BaseException” class. To handle errors, we need to add exception handling code to our program. If we provide an error message, it will be printed. Otherwise, the error will be handled without a message.

Syntax of AssertionError in Python

assert condition, error_message(optional)

Here, the “condition” represents the expression you want to test, and “error_message” (which is optional) is the message that gets displayed if the condition evaluates to false.

The following flowchart demonstrates the working of assertion error in Python:

In the above flowchart, If the condition is not true, the program stops and returns an error called AssertionError Python.

Example 1: Creating AssertionError with Error Message

Let’s consider a scenario where we are performing a division operation, and we want to avoid division by zero:

number1 = 1
number2 = 0
assert number2 != 0, "Invalid Operation"
print(number1 / number2)

In the above code, if the “number2” value is assigned zero and divided by zero, the condition becomes false, and AssertionError with an optional message appears in the output.

Here is the output that displays the AssertionError:

Example 2: Defining Custom AssertionError Function

We can also define the custom functions that raise AssertionError based on certain conditions:

def division(x,y):
    assert y!=0, 'Invalid Operation'
    return x/y;
print(division(42, 0))

Here, the function division checks if the variable “y” is zero before proceeding with the division to raise the AssertionError.

Here is the output that displays the AssertionError:

Example 3: AssertionError While Finding the Area of Circle

The AssertionError statement can also be used while dealing with mathematical problems in Python. For example, while finding the area of the circle, the AssertionErrors is used to ensure the validity of the calculations:

def area_circle(r):
    assert (r>=0), 'Radius Cannot be Less Than Zero!'
    return (((3.14)* r) * r)
print(area_circle(3))
print(area_circle(-6))

In this example code, the assertion in the function named “area_circle()” ensures that the radius is non-negative.

The below output calculates the area of the circle for the radius with the non-negative number and retrieves an AssertionError for the radius with a negative number:

Handling Python AssertionError Exception

To prevent the Python program from abruptly terminating due to an AssertionError, the “try-except” block exception handling technique is used in Python:

try:
    number1 = 1
    number2 = 0
    assert number2 != 0, "Invalid Operation"
    print(number1 / number2)
except AssertionError as e:
    print(e)

Here, the AssertionError, when raised in the “try” block, is handled using the “except” statement. The below output displays the error message:

Steps to Prevent/Avoid Python AssertionError

To prevent Python AssertionError, follow the below steps:

  • The -O flag is utilized to turn off all Python assert statements. This flag will prevent the Python AssertionError exception/error.
  • We can use an environment variable to turn off assert statements. This will affect all processes that use or inherit this environment.
  • To prevent AssertionError in Python, we can either stop the program from reaching the assert statement or continue the program after catching the AssertionError. One way to achieve this is by using a try-except block in Python.
  • An additional option available is the PYTHONOPTIMIZE setting. When this setting is configured with a non-empty string, it is equivalent to utilizing the -O option. Alternatively, if PYTHONOPTIMIZE is set to an integer value, it is equivalent to using the -O flag multiple times.

Conclusion

The “assert statement” in Python is used to find errors in the code. If the statement is false, it will show an error message called “AssertionError”. To rectify or avoid this error, we can use different methods like using a flag or making sure the code doesn’t reach the assert statement. The “try-except” block can also be employed to handle the Python AssertionError exception.

About the author

Haroon Javed

Hi, I'm Haroon. I am an electronics engineer and a technical content writer. I am a tech geek who loves to help people to the best of my knowledge.