ValueError
PythonERRORCriticalRuntime ErrorHIGH confidence

Function argument has right type but inappropriate value

What this means

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.

Why it happens
  1. 1Trying to convert a string to an integer, but the string does not represent a valid number (e.g., `int('abc')`).
  2. 2Trying to unpack a sequence into too many or too few variables.
  3. 3Passing a value to a function that is outside its valid domain (e.g., `math.sqrt(-1)`).
How to reproduce

This error is triggered when `int()` is called with a string that cannot be parsed into an integer.

trigger — this will error
trigger — this will error
# 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.

Validate input before conversion
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.

Use a `try-except` block to handle invalid values
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.

Code examples
Triggerpython
int_val = int("hello")  # ValueError: invalid literal for int()
Handle with try/exceptpython
try:
    val = int(user_input)
except ValueError:
    print("Not a valid integer")
    val = 0
Avoid with validation firstpython
def safe_int(s: str, default: int = 0) -> int:
    return int(s) if s.lstrip("-").isdigit() else default
What not to do

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.

Sources
Official documentation ↗

cpython/Objects/exceptions.c

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Python errors