Skip to content

Assertion

In one line

An assertion (assert) checks a condition at runtime and raises AssertionError if it is false, used for debugging.

In simple words

An assertion is a debugging aid that checks a condition is true. If the condition is false, AssertionError is raised (with an optional message). The syntax is assert condition, message.

Assertions are for catching programming errors (bugs), not for handling expected runtime errors. Use them to verify invariants, preconditions, and postconditions during development.

Important: assertions can be disabled with python -O (optimized mode), which strips all assert statements. Never use assertions for validation that must run in production — use explicit if/raise instead. Assertions are for development and testing.

Example

python
def calculate_average(numbers):
    assert len(numbers) > 0, "Cannot average an empty list"
    return sum(numbers) / len(numbers)

print(calculate_average([1, 2, 3]))  # 2.0

# This raises AssertionError
# calculate_average([])

# Assertions can be disabled with: python -O script.py

assert checks a condition and raises AssertionError if false. Used for debugging, not production validation.

Common confusions

  • Confused with: exception

    The difference: An assertion checks for programming bugs and can be disabled in optimized mode. An exception (raise) handles expected runtime conditions and always runs. Use assertions for debugging; use exceptions for production error handling.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary