Python Small Checks for a Module
A small check is an assert line that tests one fact. The check passes in silence and fails loudly.
A passing check stays silent
double(3) must be 6. The assert passes, so only the print shows.
def double(n):
return n * 2
assert double(3) == 6
print("Checks passed")A check on a list
total must add 1, 2 and 3 to 6. An empty list must total 0.
def total(nums):
return sum(nums)
assert total([1, 2, 3]) == 6
assert total([]) == 0
print("Totals look right")A check with a message
This double is wrong on purpose. The check catches it and prints its message.
def double(n):
return n * 3
try:
assert double(3) == 6, "double(3) must be 6"
except AssertionError as e:
print(e)A check catches a wrong result
add subtracts instead of adding. The check catches the wrong sum.
def add(a, b):
return a - b
try:
assert add(2, 3) == 5
except AssertionError:
print("add(2, 3) is wrong")Example
def area(width, height):
return width * height
def perimeter(width, height):
return 2 * (width + height)
assert area(3, 4) == 12
assert area(0, 5) == 0
assert perimeter(3, 4) == 14
assert perimeter(1, 1) == 4
print("All checks passed")Key points
- Check: an assert line that tests one fact about the code
- Use assert to state what must be true
- A passing assert prints nothing and changes nothing
- A failing assert raises AssertionError and stops the program
- Put the check right after the function it tests
- A check with a message says what went wrong
In this example, two small functions sit side by side. Four checks test both functions. Each check states one fact. The pass line prints only when all four pass.
Note
assert tests the code, not the reader's input.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does a passing assert do?