Cookie Policy

We use cookies to operate this website, improve usability, personalize your experience, and improve our marketing. Privacy Policy.

By clicking "Accept" or further use of this website, you agree to allow cookies.

Accept
Learn Machine Learning by Doing Learn Now
You are reading solutions
alfie-grace-headshot-square2.jpg
Author: Alfie Grace
Data Scientist

Python ValueError: invalid literal for int() with base 10

LearnDataSci is reader-supported. When you purchase through links on our site, earned commissions help support our team of writers, researchers, and designers at no extra cost to you.

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

Why does this occur?

While using the int() function, there are some strict rules which we must follow.

This error is triggered in one of two cases:

  1. When passing a string containing anything that isn't a number to int(). Unfortunately, integer-type objects can't have any letters or special characters.
  2. When passing int() a string-type object which looks like a float-type (e.g., the string '56.3'). Although technically, this is an extension of the first error case, Python recognizes the special character .inside the string '56.3'.

To avoid the error, we shouldn't pass int() any letters or special characters.

We'll look at a specific example for each of these causes, along with how to implement a solution.

Cause 1: Non-numerical Arguments

As mentioned previously, one of the most common causes of the ValueError we've been looking at is passing int() an argument that contains letters or special characters.

By definition, an integer is a whole number, so an integer-type object should only have numbers (+ and - are also acceptable). As a result, Python will throw an error when attempting to convert letters into an integer.

This error can frequently occur when converting user-input to an integer-type using the int() function. This problem happens because Python stores the input as a string whenever we use input().

As a result, if you'd like to do some calculations using user input, the input needs to be converted into an integer or float.

Let's consider a basic example and create a short program that will find the sum of two values input by the user:

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

new_val = val_1 + val_2

print("\nThe sum is: ", new_val)
Out:
Enter the first value:  5
Enter the second value:  3
Out:
The sum is:  53

As you can see, we received "53" instead of the correct sum, "8". We received this output because the input must be converted to integer-type to calculate the sum correctly. We have instead added two strings together through concatenation.

So, we need to convert the values to integers before summing them, like so:

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

new_val = int(val_1) + int(val_2)

print("\nThe sum is: ", new_val)
Out:
Enter the first value:  5
Enter the second value:  3
Out:
The sum is:  8

We're now getting the correct answer.

Despite working as expected, problems can occur if users start inputting values that aren't integers.

In the example below, we have entered "Hello" as the second input:

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

new_val = int(val_1) + int(val_2)

print("\nThe sum is: ", new_val)
Out:
Enter the first value:  5
Enter the second value:  Hello
Out:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-697a6feaa0ed> in <module>
      2 val_2 = input("Enter the second value: ")
      3 
----> 4 new_val = int(val_1) + int(val_2)
      5 
      6 print("\nThe sum is: ", new_val)
ValueError: invalid literal for int() with base 10: 'Hello'

We now have an error because the value val_2 is 'Hello', which isn't a number. We can fix this by using a simple try/except block, like in the following solution.

Solution

In this scenario, there isn't much that can be done about users testing the limits of our program. One potential solution is adding an exception handler to catch the error and alert the user that their entry was invalid.

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

try:
    new_val = int(val_1) + int(val_2)
    print("\nThe sum is: ", new_val)
except ValueError:
    print("\nWhoops! One of those wasn't a whole number")
Out:
Enter the first value:  5
Enter the second value:  Hello
Out:
Whoops! One of those wasn't a whole number

Using an exception handler here, the user will receive a warning message whenever int() throws a ValueError. This solution is a common way to handle user input that will be cast to integers.

Cause 2: Float-like Strings

Passing int() a string-type object which looks like a float (e.g. '56.9'), will also trigger the ValueError.

In this scenario, Python detects the ., which is a special character, causing the error. For example, here's what happens when we pass '56.3' to int() as an argument:

Out:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-4ff8ba29c4d7> in <module>
----> 1 int("56.9")

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

Solution

int() works with floats, so the simplest way to fix the error, in this case, is to convert our string to a floating-point number first. After converting the string-type to float-type, we can successfully pass our object to the int() function:

val = float("56.9")
int(val)

The main problem with this approach is that using int() on a float will cut off everything after the decimal without round to the nearest integer.

56.9 is much closer to 57 than 56, but int() has performed a simple truncation to eliminate the decimal.

For situations where you'd prefer to round floats to their closest integer, you can add an intermediate step using the round() function, like so:

val = float("56.9")
rounded_val = round(val, 0)
int(rounded_val)

Specifying zero as our second round() argument communicates to Python that we'd like to round val to zero decimal places (forming an integer). By altering the second argument, we can adjust how many decimal numbers Python should use when rounding.

Summary

As we've discussed, passing an argument that contains letters or special characters to the int() function causes this error to occur. Integers are whole numbers, so any string-type objects passed to int()should only contain numbers, +or -.

In cases where we'd like to convert a string-type object that looks like float (e.g. '56.3') into an integer, we will also trigger the error. The error happens due to the presence of the .character. We can easily avoid the error by converting the string to a floating-point object first, as follows:

int(float('56.9'))

In cases where we'd like a number to remain a decimal, we could drop the int() function altogether and use float() to make the object a float-type. Ultimately, if you're experiencing this error, it's a good idea to think about what's going into the int() function and why that could be causing problems.

The error is straightforward to resolve once you get to the bottom of what's causing the issue.


Meet the Authors

alfie-grace-headshot-square2.jpg

Alfie graduated with a Master's degree in Mechanical Engineering from University College London. He's currently working as Data Scientist at Square Enix. Find him on LinkedIn.

Brendan Martin
Editor: Brendan
Founder of LearnDataSci

Get updates in your inbox

Join over 7,500 data science learners.