Errors
Assertions
When the assertion is true, execution continues normally. The assertion documents the function's internal expectation.
Source
def average(scores):
assert scores, "scores must not be empty"
return sum(scores) / len(scores)
print(average([8, 10]))Output
9.0When the assertion is false, Python raises AssertionError. This signals a broken assumption, not a normal recovery path.
Source
try:
average([])
except AssertionError as error:
print(error)Output
scores must not be emptyNotes
- Use
assertfor internal invariants and debugging assumptions. - Use explicit exceptions for user input, files, network responses, and other expected failures.
- Assertions can be disabled with Python optimization flags, so do not rely on them for security checks.
See also
- alternative: Exceptions
- related: Custom Exceptions
- next depth: Type Hints
Run the complete example
Expected output
9.0
scores must not be empty
Execution time appears here after you run the example.