ValueError: invalid literal for int() with base 10 (Fix)
Your script runs, then Python stops with this: ValueError: invalid literal for int() with base 10: '3.50' You gave int() a string that doesn't look like a whole number. The end of the message shows the exact text Python choked on, in quotes. So the error already tells you what's wrong. Below are the six inputs that cause it most often, and how to fix each one. I ran every example on Python 3.11,…
A ValueError can occur when attempting to convert a string to an integer using the int() function in Python. This error is triggered when the string does not resemble a whole number. There are six common causes for this error.
Firstly, an empty string causes the error. For instance, if the user presses Enter without providing any input, int() will raise the ValueError: invalid literal for int() with base 10. Similarly, empty CSV cells or split lines with empty pieces will result in the same error. To handle this case, one can catch the ValueError and assign a default value (such as 0) or request the user to input the value again.
Secondly, decimal numbers can lead to the ValueError. For example, trying to convert the string "3.50" to an integer will result in ValueError: invalid literal for int() with base 10: 3.50. To resolve this, one can first convert the string to a float and then to an integer, like so: int(float(price) * 100). Alternatively, the decimal module can be used for more precise money calculations.
Thirdly, the presence of thousands separators (commas) in the input string can cause the error. For example, "1,250,000" will raise the ValueError when passed to int(). To fix this issue, remove the commas using the replace() method, like so: int(population.replace(',', '')).
Fourthly, numbers in another base (like hexadecimal) can cause the error. For instance, "ff" raises the ValueError when converted to an integer. To correct this, specify the base in the int() function, like so: int(color, 16).
Lastly, a header or label line mixed with the numbers can also cause the error. For example, if the first line in a file is a header like "id", the int() function will raise ValueError when trying to convert it to an integer. To avoid this, skip the header line when reading the file or use the csv module to handle headers automatically.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.
