Errors

Assertions

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

assert checks an internal assumption. If the condition is false, Python raises AssertionError with an optional message.

Use assertions for programmer assumptions, not for validating user input or external data. Input validation should raise ordinary exceptions that production code expects to handle.

Assertions make invariants executable while keeping the successful path compact.

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 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.