Assertions make assumptions visible in tests. Python can disable them in optimized execution, so required input validation deserves an explicit exception.
Worked example
def add(a, b):
return a + b
assert add(2, 3) == 5
print('Passed')Result
PassedImplementation notes
A useful assertion documents the invariant that broke. Include enough test context to distinguish incorrect inputs from an incorrect transformation.
Try it yourself
Run an assertion-based sample normally and under python -O.
Open the Python example →Editorial date July 11, 2026 · Published December 6, 2026