| [ Web Proxy ] |
| Viewing: https://www.pythonbyexample.dev/examples/assertions | [Back] [Original] |
Errors
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
assert for internal invariants and debugging assumptions.9.0
scores must not be empty
Execution time appears here after you run the example.
| Web Proxy Viewer | New URL | Original Page |