Language Syntax

Assert — Python syntax

Check a condition and raise AssertionError if false. The optional message is evaluated only on failure. Optimized compilation can omit the entire statement, so use explicit checks for required validation. Do not put the condition and message into a single tuple; a nonempty tuple is truthy.

Formal Syntax & Structure

python syntaxpython
assert conditionassert condition, message

Parameters & Attributes

NameTypeDescription
conditionexpressionTruth-tested expression.
messageexpressionOptional failure information, evaluated only on failure.

Working Example

Example Snippetpython
try:    assert 2 > 3, 'invalid'except AssertionError as e:    result=str(e)print(result)
Python Reference