Lingua-e
← Errors
Python

AssertionError: What It Means and How to Fix It

Error reference

AssertionError

Language

Python

Severity

Low

When it happens

An AssertionError is raised when an assert statement's condition evaluates to False.

Potential fixes

In production code, replace assert with explicit if checks that raise ValueError or TypeError. Reserve assert for internal invariants and test code. When you see this error in tests, read the assertion message to understand what value was expected versus what was received.

Related errors

Deep dive

An AssertionError is raised when an assert statement's condition evaluates to False. assert statements are meant for internal sanity checks during development, not for input validation in production code. They can be globally disabled by running Python with the -O flag.

Why it happens

  • An assert condition that fails because the program reached an unexpected state.
  • Using assert to validate user input or external data instead of raising a proper exception.
  • A test assertion failing, for example in pytest when the actual value does not match the expected value.
  • Running code that was written with assumptions that no longer hold after a refactor.

Potential fixes

In production code, replace assert with explicit if checks that raise ValueError or TypeError. Reserve assert for internal invariants and test code. When you see this error in tests, read the assertion message to understand what value was expected versus what was received.

Examples

Python

Code that triggers the error

def divide(a, b):
    assert b != 0, "Divisor must not be zero"
    return a / b

print(divide(10, 0))

Error output

Traceback (most recent call last):
  File "app.py", line 5, in <module>
    print(divide(10, 0))
  File "app.py", line 2, in divide
    assert b != 0, "Divisor must not be zero"
AssertionError: Divisor must not be zero

Fixed code

def divide(a: float, b: float) -> float:
    if b == 0:
        raise ValueError("Divisor must not be zero")
    return a / b

try:
    print(divide(10, 0))
except ValueError as e:
    print(f"Error: {e}")

Practice in English

How would you explain an AssertionError to a fellow dev? Choose the right phrase:

"I hit an error...

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free