AssertionError in Python — What It Means and How to Fix It
What Python's AssertionError exception means and how to resolve it.
Published October 28, 2026
AssertionError is raised when an assert statement's condition is false. It is meant for catching programmer mistakes, not for validating user input.
What it means and why it happens
Assertions can be disabled with python -O, so never use them for security or input checks.
Read the full message: it names the file and line where the problem was detected, which is the best place to start.
What you see
run the code
AssertionError
Practical examples
Code that triggers it
assert 2 + 2 == 5, 'math is broken'The fix
if not (2 + 2 == 4):
raise ValueError('math is broken')
assert result is not None # internal invariantIn tests
def test_add():
assert add(2, 3) == 5Common mistakes
- Using assert for input validation.
- Relying on asserts in production (can be stripped).
- Missing helpful messages.
Key takeaways
- AssertionError: AssertionError is raised when an assert statement's condition is false.
- Read the message and the line number first.
- Fix the cause, don't just silence the error.
FAQ
assert or raise?
Use assert for internal checks, raise exceptions for invalid input.
How do I find which line caused AssertionError?
The error message and stack trace show the file and line; start there and work backwards.