Editor

ValueError: invalid literal for int() with base 10

What it means

int() was given text that is not a whole number. It accepts strings like '42' or ' 7 ', but not words, decimals such as '3.5', or an empty string. The text after the colon is exactly what it received, so '' there means the value was blank.

1. Text that is not a number at all

This raises the error

Broken
answer = 'twelve'
number = int(answer)
print(number * 2)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'twelve'

The fix

Fixed
answer = 'twelve'
try:
number = int(answer)
except ValueError:
print(f'{answer!r} is not a whole number, using 0')
number = 0
print(number * 2)
Output
'twelve' is not a whole number, using 0
0

try and except ValueError catch the bad value so the program can react instead of crashing. For positive whole numbers you can also check first with answer.isdigit().

Try fixing it yourself in the editor

2. A decimal number in the string

This raises the error

Broken
price = '3.5'
whole = int(price)
print(whole)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: invalid literal for int() with base 10: '3.5'

The fix

Fixed
price = '3.5'
whole = int(float(price)) # float() reads the decimal, int() drops it
print(whole)
print(float(price))
Output
3
3.5

int() reads only whole numbers from text. float() understands the decimal point, and int() of a float then cuts off the fraction (use round() to round instead).

Try fixing it yourself in the editor

3. An empty string from splitting a line

This raises the error

Broken
line = '10,20,30,'
total = 0
for part in line.split(','):
total += int(part)
print(total)
Output
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
ValueError: invalid literal for int() with base 10: ''

The fix

Fixed
line = '10,20,30,'
total = 0
for part in line.split(','):
if part.strip(): # skip blank pieces
total += int(part)
print(total)
Output
60

The trailing comma makes split() return a last, empty piece '', which is not a number. Skipping blank pieces, or using line.strip(',') first, avoids it.

Try fixing it yourself in the editor

When you see this error, check

  • Read the value after the colon: it is exactly what int() received.
  • Use float() first for text with a decimal point.
  • Remove commas, currency signs and units before converting, for example '1,200'.replace(',', '').
  • Wrap conversions of outside data in try / except ValueError.

All Python errors · How to read a traceback · Step through your code