Keywords and Control Flow
assert — Debugging invariants
Check an internal invariant during normal, non-optimized execution. When the condition is falsy, raise AssertionError; the optional message expression is evaluated only on failure. CPython omits assertion code at optimization level 1 or higher, so neither the condition nor message is evaluated there. Do not use assertions for required input validation, permission checks or essential side effects. Raise an explicit exception for conditions that must be enforced in every build.
Formal Syntax & Structure
python syntaxpython
assert conditionassert condition, messageWorking Example
Example Snippetpython
def average(total, count): assert count > 0, "count must be positive" return total / count
print(average(18, 3))try: average(18, 0)except AssertionError as error: print(error)