AssertionError
PythonERRORNotableLogic ErrorHIGH confidence

Assertion statement failed

What this means

Raised when an `assert` statement fails. `assert` is a debugging aid that tests a condition; if the condition is false, it raises this error, indicating a logic error in the program.

Why it happens
  1. 1A function received arguments that violate its contract (preconditions).
  2. 2The state of an object is invalid at a certain point in the code.
  3. 3The result of a calculation is not what was expected, indicating a bug.
How to reproduce

This error is raised by an `assert` statement when its condition is not met.

trigger — this will error
trigger — this will error
def process_positive_number(x):
    assert x > 0, "Input must be a positive number"
    print("Processing...")

process_positive_number(-5)

expected output

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "<stdin>", line 2, in process_positive_number
AssertionError: Input must be a positive number

Fix 1

Fix the calling code to meet the condition

WHEN The assertion is correct and the data being passed to it is wrong.

Fix the calling code to meet the condition
def process_positive_number(x):
    assert x > 0, "Input must be a positive number"
    print("Processing...")

# Fix: Call the function with a valid argument
process_positive_number(5)

Why this works

By providing data that satisfies the assertion's condition, the `AssertionError` is avoided. This usually means fixing a bug in the code that calls the function.

Fix 2

Use explicit conditional checks and raise a specific error

WHEN You are validating user input or external data, where invalid data is expected.

Use explicit conditional checks and raise a specific error
def process_user_age(age):
    if not isinstance(age, int) or age <= 0:
        raise ValueError("Age must be a positive integer")
    print("Processing age...")

Why this works

`assert` statements can be disabled in production. For validating input or API contracts, it is more robust to use standard `if/raise` checks that are always active.

Code examples
Triggerpython
x = -5
assert x > 0, "x must be positive"  # AssertionError: x must be positive
Handle with try/exceptpython
try:
    assert value > 0
except AssertionError as e:
    print(f"Assertion failed: {e}")
Avoid using explicit validationpython
def process(x):
    if x <= 0:
        raise ValueError(f"x must be positive, got {x}")
    return x * 2
What not to do

Using `assert` to validate user input or data from external systems

Assertions can be globally disabled with the `-O` and `-OO` command-line flags, which would turn off all your validation. Use `if` statements and raise `ValueError` or `TypeError` instead.

Sources
Official documentation ↗

cpython/Objects/exceptions.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors