SyntaxStudy
Sign Up
Python Beginner 3 min read

Assertions

Assertions

assert checks a condition and raises AssertionError if it is false. Used for debugging and sanity checks.

Example
def divide(a, b):
    assert b != 0, "Denominator must not be zero"
    return a / b

print(divide(10, 2))   # 5.0
print(divide(10, 0))   # AssertionError
Pro Tip

Assertions are disabled when Python runs with -O (optimized) flag.