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
Traceback (most recent call last): File "<exec>", line 2, in <module> ValueError: invalid literal for int() with base 10: 'twelve'
The fix
'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().
2. A decimal number in the string
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> ValueError: invalid literal for int() with base 10: '3.5'
The fix
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).
3. An empty string from splitting a line
This raises the error
Traceback (most recent call last): File "<exec>", line 4, in <module> ValueError: invalid literal for int() with base 10: ''
The fix
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.
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.
Related errors
All Python errors · How to read a traceback · Step through your code