Assertions in programming are statements used to verify that a certain condition is met. For example an assertion can be used to validate the correctness of an expression or calculation.

Assertions act like program's internal self-checks, they indicate whenever there is a  flaw in the program's logic.

In Python, assertions are made using the  assert keyword.

Syntax:
assert <condition>, <display message>
condition The condition to be asserted. If this condition is not met an assertion error is raised
display message An optional string that will be displayed as a custom error message if the assertion fails.
ExampleEdit & Run
def div(a, b):
   #This asserts that the value of b is not zero.
   assert b != 0, "b should never be zero."
   
   return a / b

print(div(10, 5))
Output:
2.0[Finished in 0.01128821587190032s]

AssertionError exceptions are  raised when an assertion expression is evaluated to a False boolean value.

ExampleEdit & Run
def div(a, b):
   #This asserts that the value of b is not zero.
   assert b != 0, "b should never be zero."
   
   return a / b

print(div(10, 0))
Output:
Traceback (most recent call last):  File "<string>", line 7, in <module>  File "<string>", line 3, in divAssertionError: b should never be zero.[Finished in 0.010958407074213028s]

When a program raises an AssertionError, it indicates that something has gone wrong in the execution logic.

Handling the AssertionError

When an AssertionError exception is encountered in Python, it means that a condition that the program evaluated has failed. To handle this exception, you should examine the code where the exception has occurred and debug it. This usually involves examining the values of variables involved in the assertion statement, as well as any related code.

You can also use a debugging tool such as a breakpoint or a stack trace to help identify and fix the cause of the assertion failure. Once the root cause of the exception is identified and fixed, the program should be able to resume without the exception being raised again.

The try-except blocks can also be used to catch AssertionError exceptions.  This is useful for debugging purposes, as it allows the program to detect when an assertion fails and handle it accordingly.

ExampleEdit & Run
import math

def square_root(num):
    
    assert num >= 0, "The number entered is negative"

    return math.sqrt(num)
 
num = -10   
try:
     square_root(num)
except AssertionError as e:
     #Use the absolute value of 'num'
     print(square_root(abs(num)))
Output:
3.1622776601683795[Finished in 0.01200257707387209s]