Question
What does the assert statement mean in Python, and how is it used? Explain its purpose and show practical examples of when to use it.
Short Answer
By the end of this page, you will understand how Python's assert statement checks assumptions in code, raises AssertionError when an assumption is false, and differs from normal user-input validation and error handling.
Concept
assert is a debugging aid that checks whether a condition is true while a program runs.
assert condition
If condition is True, Python continues normally. If it is False, Python stops at that point and raises an AssertionError.
age = 21
assert age >= 0
This succeeds because age >= 0 is true.
age = -3
assert age >= 0
This raises an error because a negative age violates an assumption in the program.
You can add a message to explain the failed assumption:
assert age >= 0, "Age cannot be negative"
Assertions are most useful for conditions that should never be false if the program is working correctly. They help developers catch bugs close to their cause.
An assertion is not intended for handling expected problems such as invalid form input, a missing file, or a failed network request. Those situations should usually be handled with if statements and appropriate exceptions because they can happen normally in real use.
Mental Model
Think of an assertion as a checkpoint on a factory line.
A factory assumes every bottle arriving at the labeling station has a cap. The checkpoint inspects each bottle:
- If the bottle has a cap, it continues down the line.
- If it has no cap, the line stops because something earlier is broken.
Likewise, assert checks an internal assumption:
assert cart_total >= 0, "A cart total should never be negative"
It does not fix the problem. It stops execution and points out that the program reached an impossible or unexpected state.
Syntax and Examples
The basic syntax is:
assert condition
To provide a useful failure message:
assert condition, "message explaining the assumption"
Example: checking a function result
def divide(total, people):
assert people > 0, "people must be greater than zero"
return total / people
print(divide(20, 4))
Output:
5.0
The assertion protects the function's internal requirement: division requires at least one person.
If called incorrectly:
divide(20, 0)
Python raises:
AssertionError: people must be greater than zero
Example: testing an expected result
Assertions are also common in tests:
Step by Step Execution
Consider this code:
def calculate_discount(price, percentage):
assert price >= 0, "price cannot be negative"
assert 0 <= percentage <= 100, "percentage must be from 0 to 100"
return price * (percentage / 100)
result = calculate_discount(80, 25)
print(result)
Execution proceeds as follows:
- Python calls
calculate_discount(80, 25). - It evaluates
price >= 0. 80 >= 0isTrue, so the first assertion does nothing and execution continues.- It evaluates
0 <= percentage <= 100. 0 <= 25 <= 100isTrue, so the second assertion also succeeds.- The function calculates
80 * (25 / 100), which is20.0. - The function returns
20.0.
Real World Use Cases
Assertions can document and check important developer assumptions, including:
- Algorithm invariants: A sorted-list algorithm can assert that indexes stay within valid bounds.
- Internal function contracts: A helper function can assert that it received an already-normalized value.
- Data pipeline checks: A transformation step can assert that a required column exists after an earlier processing step.
- State checks: A game or workflow can assert that an object is in a valid internal state before moving to the next stage.
- Tests: Test code commonly asserts that actual results match expected results.
Example of checking an internal data-processing assumption:
def average(scores):
assert scores, "average requires at least one score"
return sum(scores) / len(scores)
This is appropriate when an empty list indicates a programmer error or a broken earlier step. If empty input is a normal possibility from users or an API, handle it explicitly instead.
Real Codebase Usage
In real projects, assertions are usually kept focused on programmer mistakes and impossible states.
Guard clauses for expected invalid input
For public functions, APIs, or user input, use an explicit check and raise a suitable exception:
def create_account(username):
if not username.strip():
raise ValueError("username is required")
return {"username": username}
This remains active in all normal Python runs.
Assertions after internal normalization
def format_country_code(code):
normalized = code.strip().upper()
assert len(normalized) == 2, "normalization should produce a two-letter code"
return normalized
This pattern is useful only if earlier code guarantees the format. Otherwise, replace the assertion with validation.
Tests
Python's built-in unittest framework provides methods such as self.assertEqual(). The popular pytest framework intentionally uses plain Python statements:
Common Mistakes
Using assert for user validation
This is unreliable:
# Do not rely on this for production validation.
assert password
Assertions can be disabled when Python runs with optimization enabled, such as python -O app.py. Use normal validation instead:
if not password:
raise ValueError("password is required")
Expecting assert to return a value
assert is a statement, not an expression that produces True or False.
# Incorrect
is_valid = assert 5 > 0
Write the condition separately if you need its Boolean value:
is_valid = 5 > 0
assert is_valid
Using assertions for recoverable errors
Comparisons
| Tool | Best use | Disabled with python -O? | What happens on failure? |
|---|---|---|---|
assert condition | Catching programmer mistakes and broken internal assumptions | Yes | Raises AssertionError |
if condition: | Branching based on normal program conditions | No | Runs selected code block |
if not condition: raise ValueError(...) | Validating arguments or user input | No | Raises a chosen exception |
try / except | Recovering from operations that may fail, such as file or network access | No |
Cheat Sheet
# Check a condition
assert condition
# Check a condition with an explanatory message
assert condition, "explanation"
- If the condition is
True, execution continues. - If the condition is
False, Python raisesAssertionError. - Assertions are for internal assumptions and programmer errors.
- Do not use them as the only validation for user input, API requests, files, or other expected runtime failures.
- Assertions may be disabled with
python -O. - Keep assertion messages specific and useful.
assert quantity >= 0, "inventory quantity cannot be negative"
For required runtime validation, prefer:
if quantity < 0:
raise ValueError("quantity cannot be negative")
FAQ
What does assert do in Python?
It checks that a condition is true. If the condition is false, Python raises AssertionError.
Does assert print anything when it succeeds?
No. A successful assertion produces no output and execution continues.
How do I add a message to an assertion?
Add a comma followed by a string:
assert total > 0, "total must be positive"
Should I use assert to validate user input?
No. Use if and raise a suitable exception, because assertions can be disabled and user mistakes are expected runtime conditions.
Can Python assertions be disabled?
Yes. Running Python with the -O optimization option disables assertion checks.
What exception does a failed assertion raise?
It raises AssertionError. If you supplied a message, that message appears with the error.
Is assert useful in tests?
Yes. Assertions are a standard way to state expected results. For example, pytest commonly uses plain statements.
Mini Project
Description
Build a small function that calculates the average of a completed set of review scores. The function uses assertions to verify internal assumptions: the caller must provide scores, and every score must already be in the valid 1-to-5 range. This demonstrates how assertions can protect a trusted internal workflow.
Goal
Create a function that returns the average review score and clearly fails when its internal assumptions are violated.
Requirements
The requirements field must be an array, not a string.
Keep learning
Related questions
@staticmethod vs @classmethod in Python Explained
Learn the difference between @staticmethod and @classmethod in Python with clear examples, use cases, mistakes, and a mini project.
Add Rows to a Pandas DataFrame in Python
Learn how to add rows to a Pandas DataFrame, why repeated row appends are slow, and when to use loc, concat, or record lists.
Call a Function by Name in a Python Module
Learn how to call a function by name in a Python module using strings, getattr, and safe patterns for dynamic function dispatch.