Errors

Assertions

assert documents internal assumptions and fails loudly when they are false.

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.0
assert condTrue · passFalse · AssertionError
assert tests a condition; True passes silently, False raises AssertionError with the optional message.

When 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 empty

Notes

See also

Run the complete example

Example code

Expected output

9.0
scores must not be empty

Execution time appears here after you run the example.