0
0
PythonConceptBeginner · 3 min read

What is Assertion in Python: Simple Explanation and Usage

In Python, an 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.

python
def check_positive(number):
    assert number > 0, "Number must be positive"
    print(f"{number} is positive")

check_positive(5)
check_positive(-3)
Output
5 is positive Traceback (most recent call last): File "<stdin>", line 6, in <module> File "<stdin>", line 2, in check_positive AssertionError: Number must be positive
🎯

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 AssertionError stops 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

Use assert to check conditions that must be true during development.
An assertion failure raises an AssertionError and stops the program.
Assertions help catch bugs early by verifying your assumptions.
Do not use assertions for handling expected user errors.
Assertions can be disabled in optimized Python runs to improve performance.