All Python errors
AssertionError in Python: a check failed
AssertionError means the condition written after assert turned out to be False; the text after the comma explains what was expected. To fix it, find why the value breaks the condition and correct the value or the check.
Code with the error
age = -4
assert age >= 0, "age cannot be negative"
print("Age:", age)
Error message (Python 3.12, last line)
Corrected code
age = 4
assert age >= 0, "age cannot be negative"
print("Age:", age)
Output
Age: 4
Common causes
- The data really is wrong, and the check caught it.
- The condition is written backwards, for example < instead of >.
- Fractional numbers are compared with ==, such as 0.1 + 0.2 == 0.3.
- A function returns a different value from the one the check expects.
Practise in the course
Lesson: ConditionsFrequently asked questions
Should I just delete the assert line?
No. It hides the problem: the wrong value stays in the program.
Should assert check what a user types?
Use if for that. Python can be started in a mode that skips every assert.