ValueError: invalid literal for int() with base 10
ValueError: invalid literal for int() with base 10 in Python means int() was given a string that is not a whole number. The message ends with the exact string it choked on.
How do I fix ValueError: invalid literal for int() with base 10?
ValueError: invalid literal for int() with base 10 means int() got a string that is not a whole number. The end of the message shows the bad string. '' means an empty value, '3.5' needs float(), '1,000' needs the comma removed, and 'age' is often a CSV header row. Print repr(value) before converting to see it clearly.
- 1. Read the quoted valueThe text after the colon is the exact string int() rejected. '' means an empty string.
- 2. Use float() for decimalsint("19.99") fails. Use float("19.99"), or int(float("19.99")) if you want a whole number.
- 3. Skip headers and blanksSkip the CSV header row and filter out empty fields before calling int().
What does ValueError: invalid literal for int() with base 10 mean?
int() accepts an optional sign, digits, and surrounding whitespace — nothing else. A decimal point, a comma, an empty string or a stray word all raise ValueError. Read the end of the message carefully: invalid literal for int() with base 10: '' means the string was empty, which is a different bug from '3.5'.
Why does ValueError: invalid literal for int() with base 10 happen?
1. A decimal number
int("3.5") fails. int() will drop the decimals of a float like 3.5, but it will not parse a decimal string.
Breaks
price = int("19.99")Works
price = float("19.99")
# or a whole number: int(float("19.99"))2. An empty string
A blank line in a file, an empty form field, or a trailing comma in a CSV row gives "".
Breaks
nums = [int(x) for x in "1,2,,4".split(",")]Works
nums = [int(x) for x in "1,2,,4".split(",") if x.strip()]3. Thousands separators or units
"1,000" and "42px" are not numbers to int().
Breaks
n = int("1,000")Works
n = int("1,000".replace(",", ""))4. A header row or placeholder text
The first CSV line is "age", or a missing value is written as "N/A".
Breaks
for row in rows:
ages.append(int(row[1]))Works
for row in rows[1:]: # skip the header
if row[1].isdigit():
ages.append(int(row[1]))How to find it in your own code
Print repr(value) just before the int() call — repr shows quotes, spaces and empty strings that print() hides. When the input is user-supplied, wrap the conversion in try/except ValueError and handle the bad value deliberately rather than letting it crash.
Try it: fix this bug
easyparse_price("3.50") crashes: ValueError: invalid literal for int() with base 10: '3.50'.
def parse_price(text):
return int(text)More challenges with this error
Each of these challenges runs into this error. Find the bug and fix it, no install and no account needed.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.