Online Tutorials & Training Materials | STechies.com
Register Login

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

05 Aug 2019 1:47 pm || 0

When you have to do some calculation on a string in python, first you need to convert this 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

Example:

stringvalue='Hello World';
int(stringvalue)

Output:

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

Correct Example:

stringvalue='343';
print(int(stringvalue))

Output:

Output: 343

Error with Floating-Point Numbers

This error occurs when we pass a string with decimal “23.89.”

For Example:

stringvalue='22.33';
int(stringvalue)

Output:

Traceback (most recent call last):
  File "t.py", line 9, in <module>
    int(stringvalue)
ValueError: invalid literal for int() with base 10: '22.33'

Solution by using isdigit():

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

inputvalue=input("Type a number: ")
if inputvalue.isdigit():
  print(inputvalue)
else:
print("Input is not a digit: " + inputvalue)

Output:

Type a number: 33.33
Input is not a digit: 33.33

Solution by using exception handling (try/except):

inputvalue=input("Type a number: ")
try:
  number = int(inputvalue)
  print(number)
except ValueError:
print("Input is not a digit: " + inputvalue)

Output:

Type a number: 33.33
Input is not a digit: 33.33