AssertionError in Python: Causes and Fixes
AssertionError happens when an assert statement checks a condition and that condition is False.
This error usually means your program reached a state that the code assumed should never happen. It is common in debugging, tests, and code that checks important assumptions.
Quick fix
age = 20
assert age >= 18
name = ""
assert name, "name must not be empty"
AssertionError happens when an assert condition is False. To fix it:
- Check whether the condition is correct
- Check whether the variable value is correct
- Add a useful message to the
assert - Do not use
assertfor normal user input validation
For broader background, see Python errors and exceptions explained.
What AssertionError means
AssertionError is raised when an assert statement fails.
An assert statement is a quick way to say:
- "This condition should be true"
- "If it is not true, stop the program here"
For example, if your code assumes a number must be positive, you might write an assertion to check that assumption.
Assertions are often used:
- While debugging
- In tests
- To catch incorrect program states early
Basic syntax of assert
There are two common forms.
Basic form:
assert condition
With a custom message:
assert condition, "message"
The second form is usually better because it tells you what went wrong.
Example:
age = 16
assert age >= 18, "age must be at least 18"
If the condition is false, Python raises AssertionError with the message.
Example that causes AssertionError
Here is a simple example:
number = -5
assert number > 0, "number must be positive"
Output:
Traceback (most recent call last):
File "example.py", line 2, in <module>
assert number > 0, "number must be positive"
AssertionError: number must be positive
Why did this fail?
- The condition is
number > 0 - The value of
numberis-5 -5 > 0isFalse
So Python raises AssertionError.
Here is the same idea without a message:
number = -5
assert number > 0
Output:
Traceback (most recent call last):
File "example.py", line 2, in <module>
assert number > 0
AssertionError
This works, but it is harder to debug because the error gives less information.
Common causes
AssertionError usually happens for one of these reasons:
- An
assertcondition evaluates toFalse - Unexpected input was passed to a function
- A variable has the wrong value because of earlier code
- The code made an assumption that is not always true
assertwas used for user input validation- No custom message was added, so the error is harder to understand
Example of a variable changing earlier in the program:
count = 10
count = count - 15
assert count >= 0, "count should not be negative"
The real problem may be earlier in the code, not on the assert line itself.
How to fix AssertionError
Start by checking the exact condition that failed.
1. Check the assert condition
Make sure the condition matches what you really want to test.
score = 0
assert score >= 0, "score must not be negative"
This assertion is fine if 0 is allowed.
But if you wrote this by mistake:
score = 0
assert score > 0, "score must be positive"
then 0 will fail even if it should be valid.
2. Print values before the failing line
If you are not sure why the assertion failed, print the values first.
number = -5
print(number)
print(number > 0)
assert number > 0, "number must be positive"
Output:
-5
False
Traceback (most recent call last):
...
AssertionError: number must be positive
Useful debugging commands include:
print(value)
print(type(value))
print(condition_result)
help(assert)
python your_script.py
3. Make sure the data is valid
If a function expects a certain kind of input, check what you passed into it.
def divide_total(total, people):
assert people > 0, "people must be greater than 0"
return total / people
print(divide_total(100, 4))
This works.
But this will fail:
def divide_total(total, people):
assert people > 0, "people must be greater than 0"
return total / people
print(divide_total(100, 0))
The fix is to pass a valid value, or change the function so it handles invalid input more clearly.
4. Add a helpful message
A good message makes debugging much faster.
Less helpful:
username = ""
assert username
More helpful:
username = ""
assert username, "username must not be empty"
5. Use if and raise a normal exception for user input
If you are validating normal input from a user, assert is usually not the best tool.
Use an if statement and raise a clear exception instead. See also how to raise an exception in Python.
def set_age(age):
if age < 0:
raise ValueError("age cannot be negative")
return age
This is clearer than using assert for ordinary bad input.
If you want to handle errors without stopping the whole program, read how to handle exceptions in Python.
AssertionError in functions
A function may use assert to check assumptions about its inputs.
Example:
def greet(name):
assert isinstance(name, str), "name must be a string"
return "Hello, " + name
print(greet("Maya"))
This works because "Maya" is a string.
But this fails:
def greet(name):
assert isinstance(name, str), "name must be a string"
return "Hello, " + name
print(greet(123))
Output:
Traceback (most recent call last):
...
AssertionError: name must be a string
This can be useful when a function should only be called in a certain way.
But there is an important idea here:
assertchecks programmer assumptions- It is not the same as handling normal user mistakes
If a user might enter bad data, explicit exceptions are usually better.
assert vs raising an exception yourself
It helps to know when to use assert and when to use raise.
Use assert when:
- You are checking an internal assumption
- You are debugging code
- You want to fail early if something impossible happened
Example:
items = [1, 2, 3]
index = 1
assert 0 <= index < len(items), "index should be within list bounds"
print(items[index])
Use raise ValueError or raise TypeError when:
- A user gives bad input
- A function argument is invalid
- You want a clear, intentional error in production code
Example:
def calculate_discount(price):
if price < 0:
raise ValueError("price cannot be negative")
return price * 0.9
This is usually easier to understand than an assertion for user input.
For more on related exception types, compare this with ValueError in Python: causes and fixes and TypeError vs ValueError in Python explained.
Debugging steps
When you see AssertionError, follow these steps:
- Read the traceback carefully
- Find the exact
assertline that failed - Look at the condition inside the
assert - Check the values used in that condition
- Print variables before the failing line
- Test with small known values
Example:
value = "10"
print(value)
print(type(value))
print(value.isdigit())
assert isinstance(value, int), "value must be an integer"
Output:
10
<class 'str'>
True
Traceback (most recent call last):
...
AssertionError: value must be an integer
This tells you the problem is not the number itself. The problem is that the value is a string, not an integer.
Related errors and confusion points
Beginners often confuse AssertionError with other errors.
AssertionError vs ValueError
AssertionErrormeans an assertion failedValueErrormeans the value has the right type, but the value is not acceptable
Example of ValueError:
int("hello")
This raises ValueError because "hello" cannot be converted to an integer.
AssertionError vs TypeError
AssertionErrorcomes from a failedassertTypeErrorhappens when an operation uses the wrong type
Example of TypeError:
"5" + 2
This fails because Python cannot add a string and an integer together.
AssertionError vs syntax errors
A syntax error means the code itself is written incorrectly.
Example:
if True
print("hello")
That is different from AssertionError, which happens when the code runs and a condition is false.
FAQ
What causes AssertionError in Python?
It happens when an assert statement checks a condition and that condition is False.
How do I fix AssertionError?
Check the assert condition, inspect the values used in it, and make sure your program data matches what the code expects.
Should I use assert for user input validation?
Usually no. For user input, use normal checks with if statements and raise exceptions like ValueError when needed.
What is the difference between AssertionError and ValueError?
AssertionError means an internal check failed. ValueError usually means a value is the right type but not acceptable.