Brainlag
  1. Library
  2. Debugging
  3. Python

ValueErrorWhat is a ValueError?

A ValueError means a function got the right type of value but a value it cannot use, like int("twelve") or int("4.5").

Python5 min

What ValueError means

Output
ValueError: invalid literal for int() with base 10: 'twelve'

int() is happy to take a string, so the type is fine. The problem is this particular string: 'twelve' is not digits. A ValueError means "right kind of thing, wrong contents".

The usual causes:

  • Words or symbols where digits should be. int("twelve"), int("12 points"), int("").
  • A decimal given to int(). int("4.5") fails. Use float() for decimals.
  • Unpacking the wrong number of items. a, b = [1, 2, 3].

How to find it

The last line quotes the exact value that failed, which is the clue. Ask where that value came from: typed input, a file, a split line. If the data is wrong, fix the data. If bad data is expected to turn up, catch it with try and except ValueError.

Run it: a number written as a word

Press Run and read the error from the bottom up.

main.py to run
answer = "twelve"
age = int(answer)
print(age + 1)

The film rating that will not average

Three friends rated a film out of 10. This should print Average: 8.17. Fix it.

exercise_1.py to run
ratings = ["8", "7.5", "9"]
total = 0
for r in ratings:
    total = total + int(r)
print(f"Average: {total / len(ratings):.2f}")

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.