Online Tutorials & Training Materials | STechies.com
Register Login
Advertisement

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

|| 0

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

When you have to do some calculation on string in python, first you need to convert this string into integer by using function int().

This function takes string as input and convert it into integer.

If we pass non-integer value as 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 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

 


Advertisement
Advertisement
Advertisement