Question

Python assert Statement: Purpose, Usage, and Examples

pythonexceptionassertassertion

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.

Take Quiz

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:

def add(left, right):
    return left + right

assert add(2, 3) == 5

This confirms that add(2, 3) produces the expected value.

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:

  1. Python calls calculate_discount(80, 25).
  2. It evaluates price >= 0.
  3. 80 >= 0 is True, so the first assertion does nothing and execution continues.
  4. It evaluates 0 <= percentage <= 100.
  5. 0 <= 25 <= 100 is True, so the second assertion also succeeds.
  6. The function calculates 80 * (25 / 100), which is 20.0.
  7. The function returns 20.0.
  8. print(result) displays 20.0.

Now consider calculate_discount(80, 150):

  1. The price assertion succeeds.
  2. The percentage assertion evaluates to False.
  3. Python raises AssertionError: percentage must be from 0 to 100.
  4. The calculation and print call do not continue.

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.

Take Quiz

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 assert statements:

def test_total_includes_tax():
    total = 100 * 1.2
    assert total == 120

Test assertions are valuable because a failed assertion clearly indicates that expected behavior changed or a bug was introduced.

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

A missing file or unavailable API can be expected in production. Handle it with exceptions or conditional logic:

from pathlib import Path

path = Path("settings.json")
if not path.exists():
    raise FileNotFoundError("settings.json was not found")

Writing unclear messages

Avoid messages that merely repeat the failed condition:

assert balance >= 0, "balance >= 0"

Explain why the condition matters:

assert balance >= 0, "A completed transaction must not create a negative balance"

Depending on side effects inside an assertion

Do not put important work in an asserted expression:

# Bad: save_record() may not run when assertions are disabled.
assert save_record(record)

Run the operation normally and check its result with explicit error handling.

Comparisons

ToolBest useDisabled with python -O?What happens on failure?
assert conditionCatching programmer mistakes and broken internal assumptionsYesRaises AssertionError
if condition:Branching based on normal program conditionsNoRuns selected code block
if not condition: raise ValueError(...)Validating arguments or user inputNoRaises a chosen exception
try / exceptRecovering from operations that may fail, such as file or network accessNoCatches and handles exceptions

assert versus if

# Assertion: this should be impossible if surrounding code is correct.
assert status in {"pending", "paid", "cancelled"}

# Conditional logic: this is an expected choice in the program.
if status == "paid":
    send_receipt()

Use assert to expose a broken assumption. Use if to make a normal decision.

Take Quiz

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 raises AssertionError.
  • 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 assert statements.

Can an assertion check more than one condition?

Yes, combine conditions with Boolean operators:

assert 0 <= score <= 100, "score must be between 0 and 100"
Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more