Assertion Error Python (original) (raw)

Last Updated : 07 Apr, 2025

Assertions are a powerful tool in Python used to check that conditions hold true while your program runs. By using the assert statement, we can declare that a certain condition must be true at a specific point in our code. If the condition is true, execution continues normally; if it is false, an **AssertionError is raised and the program stops (or the error is caught if handled).

This mechanism is especially useful for catching bugs early, validating input values and enforcing invariants in your code.

Syntax

assert condition, error_message

**Parameters:

Examples of assertion

Example 1: Basic Assertion with Error Message

Python `

x = 1 y = 0 assert y != 0, "Invalid Operation: Denominator cannot be 0" print(x / y)

`

**Output :

Traceback (most recent call last):
File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in
assert y!=0, "Invalid Operation" # denominator can't be 0
AssertionError: Invalid Operation

**Explanation:

The default exception handler in python will print the error_message written by the programmer, or else will just handle the error without any message, both the ways are valid.

Example 2: Handling an AssertionError

Assertions can be caught and handled using a try-except block. This is useful when you want to gracefully handle the error and provide custom output.

In Example 1 we have seen how the default exception handler does the work. Now let’s dig into handling it manually:

Python `

try: x = 1 y = 0 assert y != 0, "Invalid Operation: Denominator cannot be 0" print(x / y) except AssertionError as error: print(error)

`

Output

Invalid Operation: Denominator cannot be 0

**Explanation:

Practical Application: Testing a Function

Assertions are often used in testing to validate that functions produce the expected results. Consider the following example for solving a quadratic equation.

Example 3: Roots of a Quadratic Equation

Python `

import math

def quadratic_roots(a, b, c): try: assert a != 0, "Not a quadratic equation: coefficient of x^2 cannot be 0" D = (b * b - 4 * a * c) assert D >= 0, "Roots are imaginary" r1 = (-b + math.sqrt(D)) / (2 * a) r2 = (-b - math.sqrt(D)) / (2 * a) print("Roots of the quadratic equation are:", r1, r2) except AssertionError as error: print(error)

quadratic_roots(-1, 5, -6) # Expected valid roots quadratic_roots(1, 1, 6) # Expected error: roots are imaginary quadratic_roots(2, 12, 18) # Expected valid roots

`

Output

Roots of the quadratic equation are: 2.0 3.0 Roots are imaginary Roots of the quadratic equation are: -3.0 -3.0

**Explanation:

Some Other Practical Applications of Assertions: