Python assert Statement: Check Assumptions While Debugging
An assert statement checks that something is true. If it is false,
Python stops at once with an AssertionError.
This lesson shows how to use assert to catch a wrong value where it first
appears. Read Debugging first.
Check a value with assert
Write assert, then a condition. A passing assert does nothing.
total = 3 + 5
assert total == 8
print("total is", total)
This prints total is 8. The check passed silently.
Stop as soon as a value is wrong
A failing assert stops the program on that line. Add a message after a comma to say what went wrong.
scores = [3, 5, 2]
total = 0
for score in scores:
total = score
assert total == 10, "total should be 10, got " + str(total)
print("never reached") # the assert above raises AssertionError
The error reads AssertionError: total should be 10, got 2. The bug shows up
right where the assumption broke, not later when the wrong total is used.
Test a function with a few asserts
A short list of asserts checks a function against known answers, including edge cases. Run it after every fix.
def sum_up_to(limit):
total = 0
for number in range(1, limit + 1):
total = total + number
return total
assert sum_up_to(3) == 6
assert sum_up_to(1) == 1
assert sum_up_to(0) == 0
print("all checks passed")
This prints all checks passed.
When not to use assert
Use assert for things that should never happen if your code is right. Do
not use it to check user input. Python skips every assert when run with the
-O option:
python -O my_program.py
To reject bad input, use an if and a message, or raise an error yourself.
See also: Data validation, Raising exceptions, Reading a traceback.
Your turn
largest should return the biggest number in a list. Add three asserts that
check it with [3, 9, 4], [7] and [-5, -2]. Fix the bug they reveal, then
print all checks passed.
def largest(numbers):
best = 0
for number in numbers:
if number > best:
best = number
return best
# add three asserts, fix the bug in largest, then print "all checks passed"
Expected output
all checks passed