Assertions are programming constructs used to check assumptions about the state of a program. An assertion tests whether a specific condition is true—if it isn't, an error is typically raised and the program stops.
x = 10
assert x > 0 # passes
assert x < 5 # raises AssertionError, since x is not less than 5
They help with debugging: you can verify that certain conditions in code hold true during development.
They document implicit assumptions, e.g., “At this point, the list must have at least one item.”
They are mainly used during development—assertions are often disabled in production code.
Assertions are meant to catch programmer errors, not user input or external failures. For example:
assert age > 0
→ inappropriate if age
comes from user input.
Instead, use: if age <= 0: raise ValueError("Age must be positive.")