Python assert Exercises: Testing Functions with Assertions
An assertion is a claim about your program. When the claim is false, Python raises AssertionError and stops the current path. That makes assert a useful teaching and testing tool, provided you do not confuse it with input validation.
State the expected result
assert add(2, 3) == 5 turns an expectation into executable code. If the implementation changes, the check fails at the exact line. Keep each assertion focused on one behavior so failures are easy to diagnose.
def add(a, b):
return a + b
assert add(2, 3) == 5
print("ok")One clear claim
Add a message that explains the gap
A message after the comma is shown when the assertion fails. State the expected value and, when useful, the actual input. Avoid messages such as failed: it only repeats what the exception already says.
def double(n):
return n * 2
try:
assert double(3) == 7, "double(3) should be 6"
except AssertionError as error:
print(error)A useful failure message
Catch a failure to study it
AssertionError is an ordinary exception, so a small example can catch it and print the message. In a real test run, let the failure propagate to the test runner. Hiding it would defeat the purpose of the check.
try:
assert 1 == 2, "one is not two"
except AssertionError as error:
print(error)Inspect without hiding
Test normal and boundary input
A function that works for 2 and 3 may still fail for 0, an empty list, or a negative number. Add one boundary case to each small test set. Assertions make those cases part of the code instead of a comment.
def total(values):
return sum(values)
assert total([]) == 0
assert total([1, 2, 3]) == 6
print("boundary and normal cases pass")Include an edge case
Know what assert is not for
Do not use assert to validate passwords, permissions, or user input. Python's -O flag removes assert statements, so a security check written that way can disappear. Raise ValueError or a custom exception for validation instead.
def positive(n):
if n <= 0:
raise ValueError("n must be positive")
return n
print(positive(3))Validation belongs in an if
Your practice checklist
- Use assert for tests and internal invariants.
- Add a message that states the expected behavior.
- Test at least one boundary case.
- Catch AssertionError only when studying a failure.
- Use explicit exceptions, not assert, for user input validation.
Common questions
Can assert be disabled?
Yes. Running Python with -O removes assert statements, so they must not guard security or required validation.
What exception does assert raise?
AssertionError. The optional message becomes the exception text.
Should every function have asserts?
No. Put them where an assumption is important and a failure should be loud, especially in tests and internal helpers.
Practice assertions
12 questions on assert, messages, AssertionError, boundary cases, and validation.
Keep reading: