A ValueError is raised in Python when a function receives an argument of the correct type but with an inappropriate value. The type is right, but the actual content or number does not make sense for that operation.
Why it happens
- •Passing a non-numeric string to int() or float().
- •Providing a value outside the valid range for an operation (e.g. math.sqrt(-1)).
- •Unpacking a sequence into the wrong number of variables.
- •Passing an empty string where a non-empty string is required.
Examples
Code that triggers the error
number = int("hello")
print(number)Error output
Traceback (most recent call last):
File "app.py", line 1, in <module>
number = int("hello")
ValueError: invalid literal for int() with base 10: 'hello'How to fix it
Validate input values before passing them to functions that have strict requirements. Use try/except ValueError to handle user input gracefully. Check documentation for valid value ranges when calling math or conversion functions.
Fixed code
raw = "hello"
try:
number = int(raw)
except ValueError:
print(f"'{raw}' is not a valid number")
number = 0
print(number) # 0Related errors
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free