Register Login

Valueerror: Invalid literal for int() with base 10:

Updated May 03, 2020

In this article we will learn about the error “ValueError: Invalid literal for int with base 10”. This error is raised whenever we call int() function with a string argument that can not be parsed as an integer.

When we have to do some calculation on a string in python, first we need to convert the string into an integer by using function int().

This function takes a string as input and converts it into an integer.

If we pass non-integer value as a string, it will generate value error in python “invalid literal for int() with base 10”.

Valueerror: Invalid literal for int() with base 10

Error Example:

# Initialize a string variable
stringvalue='Hello World'

# Trying to convert string to integer
invvalue = int(stringvalue)

Output:

Traceback (most recent call last):
File "pyprogram.py", line 6, in <module>
invvalue = int(stringvalue)
ValueError: invalid literal for int() with base 10: 'Hello World'

Explanation:
In the above example, we assigned a string value to the variable ‘stringvalue’. And then passed it as an argument to the built-in function int(). Thus the error is raised at line 6 int(stringvalue) of the code.

Correct Example:

# Initialize a string variable
stringvalue='23'

# Trying to convert string to integer
invvalue = int(stringvalue)

Output:

String Value: 23

Explanation:
In the above example, we passed an integer value as a string to the variable ‘stringvalue’. Then we converted the variable to an integer using the built-in function int(). Hence no error is encountered.

Solution by Using isdigit() Method:

In this example, we will use function isdigit() to check whether the value is number or not?

Example:

# Initialize a string variable
stringvalue='23'

# Check if string is numeric or not
if stringvalue.isdigit():
    print('String value: ', stringvalue)
else:
    print("Variable is not Numaric: " + stringvalue)

Output:

String Value: 23

 

Solution by Using Exception Handling (Try/except):

# Initialize a string variable
stringvalue='23'

try:
    number = int(stringvalue)
    print('String Value: ',number)
except ValueError:
    print("String is not Numaric: " + inputvalue)

Output:

String Value: 23

Conclusion:
In this article, we learned about the errorValueError: Invalid literal for int with base 10”. To avoid this error find where the string value is declared and then fix the problem at the origin by converting it into the desired data type.


×