Code with the error

age = -4
assert age >= 0, "age cannot be negative"
print("Age:", age)

Error message (Python 3.12, last line)

AssertionError: age cannot be negative

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: Conditions

Frequently 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.