Testing with assert
assert raises an AssertionError when a condition is false, which makes it a quick check. For real projects use the unittest module or pytest: write small tests that call your functions and compare the result with what you expect.
Example
def add(a, b):
return a + b
assert add(2, 3) == 5
assert add(-1, 1) == 0
print("All checks passed")
try:
assert add(1, 1) == 3, "1 + 1 should be 2"
except AssertionError as error:
print("Failed:", error)Result
All checks passed Failed: 1 + 1 should be 2
Exercise
Check that a condition holds.
add(2, 2) == 4Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.