Assertion statement failed
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.
- 1A function received arguments that violate its contract (preconditions).
- 2The state of an object is invalid at a certain point in the code.
- 3The result of a calculation is not what was expected, indicating a bug.
This error is raised by an `assert` statement when its condition is not met.
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.
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.
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.
x = -5 assert x > 0, "x must be positive" # AssertionError: x must be positive
try:
assert value > 0
except AssertionError as e:
print(f"Assertion failed: {e}")def process(x):
if x <= 0:
raise ValueError(f"x must be positive, got {x}")
return x * 2✕ 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.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev