Function argument has right type but inappropriate value
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value. This differs from `TypeError`, which is for arguments of the wrong type.
- 1Trying to convert a string to an integer, but the string does not represent a valid number (e.g., `int('abc')`).
- 2Trying to unpack a sequence into too many or too few variables.
- 3Passing a value to a function that is outside its valid domain (e.g., `math.sqrt(-1)`).
This error is triggered when `int()` is called with a string that cannot be parsed into an integer.
# The string "hello" cannot be converted to an integer
int_value = int("hello")
expected output
Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'hello'
Fix 1
Validate input before conversion
WHEN When converting user input or data from an external source that may not be clean.
text = "123a"
if text.isdigit():
int_value = int(text)
else:
print(f"Cannot convert '{text}' to an integer.")
Why this works
The `.isdigit()` string method checks if all characters in the string are digits, preventing the `ValueError`.
Fix 2
Use a `try-except` block to handle invalid values
WHEN When an invalid value is possible and you want to handle it gracefully, like by providing a default.
text = "hello"
try:
int_value = int(text)
except ValueError:
int_value = 0 # Assign a default value
print(int_value)
Why this works
The `try` block attempts the conversion, and if a `ValueError` occurs, the `except` block catches it and executes the fallback logic.
int_val = int("hello") # ValueError: invalid literal for int()try:
val = int(user_input)
except ValueError:
print("Not a valid integer")
val = 0def safe_int(s: str, default: int = 0) -> int:
return int(s) if s.lstrip("-").isdigit() else default✕ Catching `ValueError` and doing nothing (`pass`)
This can hide serious data integrity issues. If you get a `ValueError`, it means your program is receiving or creating data it cannot handle, which needs to be addressed.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev