Course contentsShow
← Python
Lesson 750 of 1,06012. Testing and DebuggingFree lesson

Validating Logic with Standard Assert Statements

Master the use of simple Python assert statements to verify expected outcomes and trigger clear failure reports during test execution.

In this lesson, you will learn how to use Python’s built-in assert statement to create lightweight, executable documentation for your code’s logic.

The Purpose of Assertions

While unit testing frameworks like pytest provide robust tools for checking expected behavior, Python includes a native assert keyword. An assertion is a sanity check—it tells the program: "I expect this condition to be True; if it isn't, stop immediately."

Assertions are not intended to handle user-facing errors (like a file missing). Instead, they are used during development to verify internal consistency, such as checking that a function’s result falls within a valid range or ensuring an object is not None before processing it.

Implementing Basic Assertions

An assert statement evaluates an expression. If the expression is True, the program continues silently. If it is False, Python raises an AssertionError. You can also provide a secondary string to explain why the logic failed:

def calculate_discount(price, percentage):
    discounted_price = price * (1 - percentage)
    
    # Ensure the logic holds up before returning
    assert discounted_price >= 0, f"Discounted price {discounted_price} cannot be negative"
    return discounted_price

# This works
print(calculate_discount(100, 0.2))

# This will trigger an AssertionError: Discounted price -10.0 cannot be negative
print(calculate_discount(100, 1.5))

When to Use Assertions

Because assert statements are meant to catch logical bugs during development, they are often used inside functions to enforce "contracts"—conditions that must be met for the function to execute successfully.

It is important to note that if you run Python with the -O (optimize) flag, these statements are stripped out to improve performance. Therefore, never use assertions for business-critical validation (like verifying user input or database permissions), as they are intended for developer-focused debugging rather than production-grade error handling.

Key Takeaway: Use the assert statement to document and verify internal assumptions about your code, providing a clear error message that surfaces bugs the moment a logical invariant is violated.