AssertionError
AssertionError
Traceback
Traceback (most recent call last):
File "main.py", line 5, in <module>
set_age(-5)
AssertionErrorWhat causes this error
An assert statement evaluated to False. This indicates a bug or violated assumption in the code's logic.
How to fix it
Fix the code so the asserted condition is true, or fix the assert if the condition was wrong. Never use assert for user input validation — use explicit if/raise instead. Remember assertions are removed with `python -O`.
Code that causes this error
def set_age(age):
assert age > 0 # fails for negative input
return age
set_age(-5)Fixed code
def set_age(age):
if age <= 0:
raise ValueError(f"Age must be positive, got {age}")
return age
try:
set_age(-5)
except ValueError as e:
print(e)About AssertionError
An AssertionError is raised when an `assert` statement fails. The assert statement is used to verify conditions that should always be true at a particular point in the program — if the condition is False, it raises AssertionError with an optional message. Assertions are a debugging and development tool, not a control flow mechanism.
They can be globally disabled by running Python with the `-O` (optimize) flag, which strips all assert statements from the bytecode. For this reason, assert should never be used for input validation, access control, or any check that must always run in production. Use assert for internal invariants, preconditions in development, and self-tests.
The unittest framework uses assertion methods (assertEqual, assertTrue, etc.) that raise AssertionError with detailed failure messages, making it the backbone of Python testing.
Common scenarios
Assert statements failing due to incorrect assumptions in code logic
Using assertions for input validation instead of explicit checks
Boolean conditions that evaluate differently than expected
Off-by-one errors and boundary condition mistakes in algorithms