Invalid literal for int() with base 10 occurs when you try to convert an invalid object into an integer. Python is good at converting between different data types. When using the int() function, we must follow a specific set of rules. If we do not follow these rules, we will raise a ValueError There are two causes of this particular ValueError:

  1. If we pass a string containing anything that is not a number, this includes letters and special characters.
  2. If we pass a string-type object to int() that looks like a float type.

To solve or avoid the error, ensure that you do not pass int() any letters or special characters.

This tutorial will go through the error in detail and how to solve it with examples.


What is a ValueError?

In Python, a value is the information stored within a certain object. You will encounter a ValueError in Python when you use a built-in operation or function that receives an argument that has the right type but an inappropriate value. Let’s look at an example of converting several a ValueError:

value = 'string'

print(float(value))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
print(float(value))

ValueError: could not convert string to float: 'string'

The above code throws the ValueError because the value ‘string‘ is an inappropriate (non-convertible) string. You can only convert numerical strings using the float() method, for example:

value = '5'
print(float(value))
5.0

The code does not throw an error because the float function can convert a numerical string. The value of 5 is appropriate for the float function.

For further reading of ValueError, go to the article: How to Solve Python ValueError: cannot convert float nan to integer.

Passing Non-numerical Arguments to int()

If we pass an argument to int() that contains letters or special characters, we will raise the invalid literal ValueError.

An integer is a whole number, so the argument provided should only have real numbers.

Let’s take the example of a program that takes an input and performs a calculation on the input.

value_1 = input("Enter the first value:  ")

value_2 = input("Enter the second value:   ")

sum_values = value_1 + value_2

print("\nThe sum is:  ", sum_values)
Enter the first value:  4

Enter the second value:   6

The sum is:   46

In this example, the program interprets the two inputs as string-type and concatenates them to give “46”. However, we want the program to interpret the two inputs as integer-type to calculate the sum. We need to convert the values to integers before performing the sum as follows:

value_1 = input("Enter the first value:  ")

value_2 = input("Enter the second value:   ")

sum_values = int(value_1) + int(value_2)

print("\nThe sum is:  ", sum_values)
Enter the first value:  4

Enter the second value:   6

The sum is:   10

The code successfully runs, but the ValueError may still occur if the user inputs a value that is not an integer. Let’s look at an example, with the input “science”:

value_1 = input("Enter the first value:  ")

value_2 = input("Enter the second value:   ")

sum_values = int(value_1) + int(value_2)

print("\nThe sum is:  ", sum_values)
Enter the first value:  4

Enter the second value:   science

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
sum = int(x) + int(y)

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

The ValueError tells us that “science” is not a number. We can solve this by putting the code in a try/except block to handle the error.

value_1 = input("Enter the first value:  ")

value_2 = input("Enter the second value:   ")

try:

    sum_values = int(x) + int(y)

    print("\nThe sum is:  ", sum_values)

except ValueError:

    print("\nYou have entered one or more values that are not whole numbers.")

You have entered one or more values that are not whole numbers

The code has an exception handler that will tell the user that the input values are not whole numbers.

Passing Float-like Strings to int()

If you pass a string-type object that looks like a float type, such as 5.3, you will also raise the ValueError. In this case, Python detects the “.” as a special character. We cannot pass strings or special characters to the int() function.

int('5.3')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
1 int('5.3')

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

Let’s look at a bakery with a program to calculate whether it has enough cakes in stock to serve customers for the day. The input field must accept decimal numbers because cakes can be half consumed, quarter consumed, etc. We are only interested in integer level precision, not half cakes or quarter cakes, so we convert the input to an integer. We can use an if statement to check whether the bakery has more than a specified number of cakes. If there are not enough cakes, the program will inform us through a print statement. Otherwise, it will print that the bakery has enough cakes for the day. The program can look as follows:

cakes = input("How many cakes are left:  ")

cakes_int = int(cakes)

if cakes_int > 8:

    print('We have enough cakes!")

else:

    print("We do not have enough cakes!")

Let’s run the code with an input of “5.4” as a string.

Enter how many cakes are left:  5.4   

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
1 cakes = int(cakes)

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

The ValueError occurs because we try to convert “5.4”, a string, as an integer. Python cannot convert a floating-point number in a string to an integer. To solve this issue, we need to convert the input to a floating-point number to convert to an integer. We can use the float() function, which returns a floating-point representation of a float, and the int() function produces an integer.

cakes = input("How many cakes are left:  ")

cakes_int = int(float(cakes))

if cakes_int > 8:

    print('We have enough cakes!")

else:

    print("We do not have enough cakes!")

Enter how many cakes are left:  5.4   

We do not have enough cakes!

The code successfully runs, with the conversion of the input to a float, the program can convert it to an integer. Based on the output, the bakery has more baking to do!

Rounding Floats

Using the int() function works with floats. However, the function will truncate everything after the decimal without rounding to the nearest integer.

cakes = float("5.7")

print(int(cakes))
5

We can see 5.7 is closer to 6 than 5, but the int() function truncates regardless of the decimal value. If it is more suitable to round floats to the nearest integer, you can use the round() function. We can make the change to the code as follows:

cakes = float("5.7")

rounded_cakes = round(cakes, 0)

print(int(cakes))
6

The second argument of the round() function specifies how many decimal places we want. We want to round to zero decimal places or the nearest integer in this example.

Summary

Congratulations on completing this tutorial! You know how the ValueError: invalid literal int() base 10 occurs and how to solve it like an expert. To summarize, integers are whole numbers, so string-type objects passed to the int() function should only contain positive or negative numbers. If we want to give a string-type object that looks like a float, int() will raise the ValueError due to the presence of the “.” special character. You must convert float-like strings to a floating-point object first and then convert to an integer. You can use the round() function to ensure the int() function does not incorrectly truncate a number and specify the number of decimal places.

Generally, ValueError occurs when the value or values used in the code do not match what the Python interpreter expects. Another common ValueError is ValueError: too many values to unpack (expected 2)

You can find other solutions to Python TypeErrors, such as TypeError: can only concatenate str (not “int”) to str, SyntaxError: unexpected EOF while parsing, and TypeError: list indices must be integers or slices, not str. If you want to learn how to write Python programs specific to data science and machine learning, I provide a compilation of the best online courses on Python for data science and machine learning.

Have fun and happy researching!