Lingua-e
← Errors
Python

ValueError: What It Means and How to Fix It

Error reference

ValueError

Language

Python

Severity

Medium

When it happens

A ValueError is raised in Python when a function receives an argument of the correct type but with an inappropriate value.

Potential fixes

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.

Related errors

Deep dive

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.

Potential fixes

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.

Examples

Python

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'

Fixed code

raw = "hello"

try:
    number = int(raw)
except ValueError:
    print(f"'{raw}' is not a valid number")
    number = 0

print(number)  # 0

Practice in English

How would you explain a ValueError to a fellow dev? Choose the right phrase:

"I hit an error...

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