ValueError
ValueError: invalid literal for int() with base 10
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
number = int("hello")
ValueError: invalid literal for int() with base 10What causes this error
A function received an argument with the right type but an invalid value. For instance, passing the string 'abc' to int(), or trying to unpack more values than available from a tuple.
How to fix it
Validate inputs before passing them to functions. Use try/except around conversions, check string content with `.isdigit()` or `.isnumeric()` before converting, and verify collection sizes before unpacking.
Code that causes this error
number = int("hello")Fixed code
text = "hello"
if text.isdigit():
number = int(text)
else:
print(f"Cannot convert '{text}' to int")About ValueError
A ValueError is raised when a function receives an argument of the correct type but an inappropriate value. The distinction from TypeError is important: the type is right, but the specific value cannot be processed. Common triggers include passing a non-numeric string to `int()` or `float()`, calling `list.remove()` with an element that is not in the list, unpacking the wrong number of values from an iterable, and passing out-of-range values to functions that expect values within a certain domain.
ValueError is one of the most frequently raised built-in exceptions and appears in data parsing, user input validation, mathematical operations, and many standard library functions. Defensive programming with try/except blocks around value conversions and input validation before processing can prevent most ValueErrors from reaching end users.
Common scenarios
Converting user input strings to numbers without validation
Unpacking iterables with an unexpected number of elements
Passing out-of-range values to mathematical functions
Processing data files with inconsistent or malformed records