Invalid literal for int() with base 10 | Error and Resolution

Python is a special language which allows you to handle errors and exceptions very well. With thousands of known exceptions and ability to handle each of them, all the errors are easily removable from the code. Keeping this in mind, we’ll discuss about the invalid literal for int() error in python.

Invalid literal for int() with base 10 is caused when you try to convert an invalid object into an integer. In Python, the int() function accepts an object and then converts it to an integer provided that it is in a readable format. So, when you try to convert a string with no integers in it, it’ll throw an error. This error belongs to the ValueError category as the value of the parameter is invalid.

Cause of invalid literal for int() with base 10 error:

ValueError in Python occurs when we one passes an inappropriate argument type. Invalid literal for int() with base 10 error is caused by passing an incorrect argument to the int() function. A ValueError is raised when we pass any string representation other than that of int.

Let us understand it in detail!

ValueError: invalid literal for int() with base 10

This error message informs that there is an invalid literal for an integer in base 10. This error means that the value that we have passed cannot be converted.

Let us consider an example:

int('1.9') 
Invalid literal for int() with base 10  example
Output

It may happen that we can think that while executing the above code, the decimal part,i.e, ‘.9’ will be truncated giving the output 1. However, this does not happen as the int( ) function uses the decimal number system as its base for conversion. This means that the default base for the conversion is 10. In the decimal number system, we have numbers from 0 to 9. Thus, int() with base = 10 can only convert a string representation of int and not floats or chars.

Let us see a few examples where this error can occur:

Example 1:

print(int("pythonpool"))
example 1

In this example the value “pythonpool” is a string value passed to the int() method which gives rise to the error.

Example 2:

print(int("41.1"))
example 2

As the value we have used here is float inside string, this gives rise to invalid literal for int() error.

Example 3:

print(int("[12]"))
example 3 Invalid literal for int() with base 10

We get error in this example as we have used list inside string.

Example 4:

print(int("(12)"))
invalid literal example 4

The error invalid literal for int() arises because we have used tuple inside string.

Example 5:

print(int("{12:1}"))
dictionary inside string which gives rise to the error

Here, we have used dictionary inside string which gives rise to the error.

Example 6:

print(int(""))
invalid literal for int() with base 10 example 6

The error arises in this code as we have used the empty string in the int() method.

Resolution to the Error: invalid literal for int() with base 10:

Using float to avoid decimal numbers:

print(int(float('1.9'))) 
1

Here, we first converted the string representation into float using the float() method. We then used the int() method to convert it into an integer.

using try-catch: to resolve invalid literal for int() with base 10

try:
    x=int("12.1")
except:
    print("Error in converting to string")
Error in converting to string

Here we have used the try-catch method to rid the invalid literal for int() with base 10 error. Basically, if the error occurs inside the try block, it is caught in the catch block, thus preventing the error.

Using isdigit():

x="12"
if x.isdigit():
    x=int(x)
    print(type(x))
<class ' int '>

In this method, we first make sure that the content inside the string is integer using the isdigit() method. As a result, the error does not occur.

Using isnumeric():

x="12"
if x.isnumeric():
    x=int(x)
    print(type(x))
<class ' int '>

Isnumeric method of the string returns the boolean stating if the string is a number. If the string contains a number then we’ll convert it to int, else not.

Invalid literal for int() with Base 10 Dataframe

This is an error while working with pandas. Python interprets numbers also as strings which are separated by commas. You can use astype function to change int. 

Example:

pd.Series(['1,2']).str.replace(',', '').astype(int)

Here, we have used the replace function to change the comma with whitespace. Later on, astype will change the format to int and now we can obtain the correct output. 

Invalid literal for int() with Base 10 Flask

The error message “invalid literal for int() with base 10” in Flask usually occurs when you are trying to convert a string to an integer using the int() function, but the string cannot be converted to a valid integer.

Here’s an example of how this error might occur in Flask:

from flask import Flask, request
app = Flask(__name__)
@app.route('/calculate')
def calculate():
    num1 = request.args.get('num1')
    num2 = request.args.get('num2')
    total = int(num1) + int(num2)
    return 'The total is: ' + str(total)

In this example, we create a Flask route called /calculate that takes two query parameters, num1 and num2, and returns their sum. We use the int() function to convert the strings num1 and num2 to integers before adding them together.

However, if a user enters a non-numeric value for either num1 or num2, we will get an “invalid literal for int() with base 10” error message when we try to convert the string to an integer.

To fix this error, we can add some error handling to our code to make sure that the input is valid before trying to convert it to an integer. One way to do this is to use the try-except block to catch any ValueError exceptions that might be raised by the int() function:

from flask import Flask, request
app = Flask(__name__)
@app.route('/calculate')
def calculate():
    num1 = request.args.get('num1')
    num2 = request.args.get('num2')
    try:
        total = int(num1) + int(num2)
        return 'The total is: ' + str(total)
    except ValueError:
        return 'Invalid input. Please enter a number.'

In this updated code, we use a try-except block to catch any ValueError exceptions that might be raised by the int() function. If an exception is caught, we return an error message to the user instead of trying to perform the calculation.

FAQs

Can we convert octal or binary to an integer using int()?

Yes we can change binary to int using 
int(number, 2)
We have set the base as 2. This is because we are changing the binary format. 

How to set base in int()?

Its syntax is int(number,2)
int(“100”, 2)  
# == 1*(2**2) + 0*(2**1) + 0*(2**0) 
For setting the base as an integer, the second argument should be 2. So basically, to set the base of an integer in Python, you can use the int() function with a second argument that specifies the base.

Conclusion:

With this, we come to the end of this article. This was an easy way to get rid of the value error in Python. If the above method does not work, then one must if the string and make sure that it does not contain any letter.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kassem Ataya
Kassem Ataya
2 years ago

print(“Welcome to a sum of series function”)
print(“Pick the intervals, and we do the rest”)
print(“\n”)
x = float(int(input(“Choose your first interval: “)))
y = float(int(input(“Choose your second interval: “)))
sum = 0
for i in range (x, y+1):
  sum += i
print(sum)

My code is good however it wont allow me to input int such as 1/30 where it keeps giving me an error

Pratik Kinage
Admin
2 years ago
Reply to  Kassem Ataya

The range() function in python, accepts two integers. In your case, both x and y are floats which are invalid arguments for range(). To fix this, you need to remove the float() part when initializing x and y.

x = int(input("Choose your first interval: "))
y = int(input("Choose your second interval: "))

This is how it should look. Replace this and you’ll be good to go.

Let me know if you have any other doubts.

Regards,
Pratik