Python ValueError
A function received an argument of correct type but inappropriate value.
Explanation
ValueError occurs when a function receives an argument that has the right type but an invalid value. For example, int("abc") raises ValueError because "abc" is a string (correct type) but cannot be converted to an integer (invalid value). This differs from TypeError which occurs when the argument type itself is wrong. ValueError commonly happens with conversions, validations, and operations that have value constraints.
Common Causes
- Invalid type conversion value
- Value out of allowed range
- Invalid format string
- Value not in allowed set
- Constraint violation
Solution
Validate input values before passing them to functions. Use try-except ValueError blocks to handle invalid values gracefully. Check value constraints (ranges, formats, allowed values) before operations. Use int(s, base=10) for safe integer parsing. For list operations like index(), check if the value exists first using the in operator. Use enum.Enum for restricted value sets.
Code Example
# ValueError from invalid conversion
age = int("abc") # ValueError: invalid literal for int()
# Fix: validate before converting
def safe_int(value, default=0):
try:
return int(value)
except ValueError:
return default
age = safe_int("abc", 0)
# ValueError from list.index()
data = [1, 2, 3]
index = data.index(5) # ValueError: 5 is not in list
# Fix: check first
if 5 in data:
index = data.index(5)
# ValueError from math.sqrt of negative
import math
result = math.sqrt(-1) # ValueError: math domain error
# Fix: check value first
if number >= 0:
result = math.sqrt(number)
else:
result = None
Error Information
Language
python
Difficulty
Beginner
Views
11
Related Errors
Python
Python PermissionError
The code lacks the necessary permissions to access a file or directory.
Python
Python TabError
The code uses inconsistent indentation by mixing tabs and spaces.
Python
Python AttributeError
The code tries to access an attribute or method that doesn't exist on an object.
Python
Python ImportError
Python found the module but failed to load it due to a dependency or attribute issue.