25. Assertions
Assertions are used to check conditions that must hold true during execution.
Basic Usage
x = 5
assert x > 0, "x must be positive"
If the condition is false, an AssertionError is raised.
When to Use Assertions
- Sanity checks during development
- Not for user input validation (can be disabled with
python -O)
Practice Challenge
Add assertions to a function that calculates the area of a rectangle, ensuring inputs are positive.
Wrap-Up
Assertions help catch bugs early by verifying assumptions in code.