What is Assertion in Python: Simple Explanation and Usage
assert statement is used to check if a condition is true during program execution. If the condition is false, it raises an AssertionError, helping catch bugs early by verifying assumptions in code.How It Works
Think of an assertion like a checkpoint in your code that confirms something you expect to be true actually is true. It's similar to a safety net that catches mistakes early before they cause bigger problems.
When Python runs an assert statement, it evaluates the condition you give it. If the condition is true, the program continues without interruption. But if the condition is false, Python stops the program and raises an AssertionError. This helps you find errors by making sure your assumptions hold at certain points.
Assertions are mainly used during development and testing to catch bugs quickly. They can be turned off in production to avoid slowing down the program.
Example
This example shows how to use assert to check if a number is positive. If the number is not positive, the program stops with an error.
def check_positive(number): assert number > 0, "Number must be positive" print(f"{number} is positive") check_positive(5) check_positive(-3)
When to Use
Use assertions to check conditions that should always be true if your program is working correctly. They are great for catching programming errors early, like verifying inputs, outputs, or internal states.
For example, you can assert that a list is not empty before processing it, or that a function's return value meets certain criteria. Assertions are not meant for handling user errors or expected problems; those should use regular error handling.
In real life, assertions are like double-checking your work before moving on, helping you avoid bigger mistakes later.
Key Points
- Assertions check assumptions: They verify conditions that should always be true.
- Raise errors if false: If the condition fails, an
AssertionErrorstops the program. - Used in development: Mainly for debugging and testing, not for user input validation.
- Can be disabled: Assertions can be turned off when running Python with the
-O(optimize) flag.
Key Takeaways
assert to check conditions that must be true during development.AssertionError and stops the program.