Wednesday, June 16, 2021

Python for Beginners: ValueError: Invalid Literal For int() With Base 10

Python ValueError: invalid literal for int() with base 10 is an exception which can occur when we attempt to convert a string literal to integer using int() method and the string literal contains characters other than digits. In this article, we will try to understand the reasons behind this exception and will look at different methods to avoid it in our programs.

What is “ValueError: invalid literal for int() with base 10” in Python?

A ValueError is an exception in python which occurs when an argument with the correct type but improper value is passed to a method or function.The first part of the message i.e. “ValueError” tells us that an exception has occurred because an improper value is passed as argument to the int() function. The second part of the message “invalid literal for int() with base 10”  tells us that we have tried to convert an input to integer but the input has characters other than digits in the decimal number system.

Working of int() function

The int() function in python takes a string or a number as first argument and an optional argument base which denotes the number format. The base has a default value 10 which is used for decimal numbers but we can pass a different value  for base such as 2 for binary number or 16 for hexadecimal number. In this article, we will use the int() function with only the first argument and the default value for base will always be zero.  This can be seen in the following examples.

We can convert a floating point number to integer as given in the following example.When we convert a floating point number into integer using int() function, the digits after the decimal are dropped from the number in the output. 


print("Input Floating point number is")
myInput= 11.1
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input Floating point number is
11.1
Output Integer is:
11

We can convert a string consisting of digits to an integer as given in the following example. Here the input consists of only the digits and hence it will be directly converted into an integer. 

print("Input String is:")
myInput= "123"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input String is:
123
Output Integer is:
123

The two input types shown in the above two examples are the only input types for which int() function works properly. With other types of inputs, ValueError will be generated with the message ”invalid literal for int() with base 10” when they are passed as arguments to the int() function. Now , we will look at various types of inputs for which ValueError can be generated in the int() function.

When does “ValueError: invalid literal for int() with base 10” occur?

As discussed above, “ValueError: invalid literal for int()” with base 10 can occur when input with an inappropriate value is passed to the int() function. This can happen in the following conditions.

1.Python ValueError: invalid literal for int() with base 10 occurs when input to int() method is alphanumeric instead of numeric and hence the input cannot be converted into an integer.This can be understood with the following example.

In this example, we pass a string containing alphanumeric characters to the int() function due to which ValueError occurs showing a message “ ValueError: invalid literal for int() with base 10”  in the output.

print("Input String is:")
myInput= "123a"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:


Input String is:
123a
Output Integer is:
Traceback (most recent call last):

  File "<ipython-input-9-36c8868f7082>", line 5, in <module>
    myInt=int(myInput)

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

2. Python ValueError: invalid literal for int() with base 10 occurs when the input to int() function contains space characters and hence the input cannot be converted into an integer. This can be understood with the following example.

In this example, we pass a string containing space to the int() function due to which ValueError occurs showing a message “ ValueError: invalid literal for int() with base 10”  in the output.

print("Input String is:")
myInput= "12 3"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input String is:
12 3
Output Integer is:
Traceback (most recent call last):

  File "<ipython-input-10-d60c59d37000>", line 5, in <module>
    myInt=int(myInput)

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

3. Python ValueError: invalid literal for int() with base 10 occurs when the input to int() function contains any punctuation marks like period “.” or comma “,”.  Hence the input cannot be converted into an integer.This can be understood with the following example.

In this example, we pass a string containing period character “.” to the int() function due to which ValueError occurs showing a message “ ValueError: invalid literal for int() with base 10”  in the output.

print("Input String is:")
myInput= "12.3"
print(myInput)
print("Output Integer is:")
myInt=int(myInput)
print(myInt)

Output:

Input String is:
12.3
Output Integer is:
Traceback (most recent call last):

  File "<ipython-input-11-9146055d9086>", line 5, in <module>
    myInt=int(myInput)

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

How to avoid “ValueError: invalid literal for int() with base 10”?

We can avoid the ValueError: invalid literal for int() with base 10 exception using preemptive measures to check if the input being passed to the int() function consists of only digits or not. We can use several ways to check if the input being passed to int() consists of only digits or not as follows.

1.We can use regular expressions to check if the input being passed to the int() function consists of only digits or not. If the input contains characters other than digits, we can prompt the user that the input cannot be converted to integer. Otherwise, we can proceed normally.

In the python code given below, we have defined a regular expression “[^\d]” which matches every character except digits in the decimal system. The re.search() method searches for the pattern and if the pattern is found, it returns a match object. Otherwise re.search() method returns None. 

Whenever, re.search() returns None, it can be accomplished that the input has no characters other than digits and hence the input can be converted into an integer as follows.

import re
print("Input String is:")
myInput= "123"
print(myInput)
matched=re.search("[^\d]",myInput)
if matched==None:
    myInt=int(myInput)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input Cannot be converted into Integer.")

Output:

Input String is:
123
Output Integer is:
123

If the input contains any character other than digits,re.search() would contain a match object and hence the output will show a message that the input cannot be converted into an integer.

import re
print("Input String is:")
myInput= "123a"
print(myInput)
matched=re.search("[^\d]",myInput)
if matched==None:
    myInt=int(myInput)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input Cannot be converted into Integer.")

Output:

Input String is:
123a
Input Cannot be converted into Integer.

2.We can also use isdigit() method to check whether the input consists of only digits or not. The isdigit() method takes a string as input and returns True if the input string passed to it as an argument consists only of digital in the decimal system  . Otherwise, it returns False. After checking if the input string consists of only digits or not, we can convert the input into integers.

In this example, we have used isdigit() method to check whether the given input string consists of only the digits or not. As the input string ”123” consists only of digits, the isdigit() function will return True and the input will be converted into an integer using the int() function as shown in the output.

print("Input String is:")
myInput= "123"
print(myInput)
if myInput.isdigit():
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
else:
    print("Input cannot be converted into integer.")

Output:

Input String is:
123
Output Integer is:
123

If the input string contains any other character apart from digits, the isdigit() function will return False. Hence the input string will not be converted into an integer.

In this example, the given input is “123a” which contains an alphabet due to which isdigit() function will return False and the message will be displayed in the output that the input cannot be converted into integer as shown below.

print("Input String is:")
myInput= "123a"
print(myInput)
if myInput.isdigit():
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
else:
    print("Input cannot be converted into integer.")    

Output:

Input String is:
123a
Input cannot be converted into integer.

3.It may be possible that the input string contains a floating point number and has a period character “.” between the digits. To convert such inputs to integers using the int() function, first we will check if the input string contains a floating point number i.e. it has only one period character between the digits or not using regular expressions. If yes, we will first convert the input into a floating point number which can be passed to int() function and then we will show the output. Otherwise, it will be notified that the input cannot be converted to an integer.

In this example,  “^\d+\.\d$” denotes a pattern which starts with one or more digits, has a period symbol ”.” in the middle and ends with one or more digits which is the pattern for floating point numbers. Hence, if the input string is a floating point number, the re.search() method will not return None and the input will be converted into a floating point number using float() function and then it will be converted to an integer as follows. 

import re
print("Input String is:")
myInput= "1234.5"
print(myInput)
matched=re.search("^\d+\.\d+$",myInput)
if matched!=None:
    myFloat=float(myInput)
    myInt=int(myFloat)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input is not a floating point literal.")

Output:

Input String is:
1234.5
Output Integer is:
1234

If the input is not a floating point literal, the re.search() method will return a None object and  the message will be shown in the output that input is not a floating point literal as follows.

import re
print("Input String is:")
myInput= "1234a"
print(myInput)
matched=re.search("^\d+\.\d$",myInput)
if matched!=None:
    myFloat=float(myInput)
    myInt=int(myFloat)
    print("Output Integer is:")
    print(myInt)
else:
    print("Input is not a floating point literal.")

Output:

Input String is:
1234a
Input is not a floating point literal.

For the two approaches using regular expressions, we can write a single program using groupdict() method after writing named patterns using re.match() object. groupdict() will return a python dictionary of named captured groups in the input and thus can be used to identify the string which can be converted to integer.

4.We can also use exception handling in python using python try except to handle the ValueError whenever the error occurs. In the try block of the code, we will normally execute the code. Whenever ValueError occurs, it will be raised in the try block and will be handled by the except block and a proper message will be shown to the user.

 If the input consists of only the digits and is in correct format, output will be as follows.

print("Input String is:")
myInput= "123"
print(myInput)
try:
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
except ValueError:
    print("Input cannot be converted into integer.")

Output:

Input String is:
123
Output Integer is:
123

If the input contains characters other than digits such as alphabets or punctuation, ValueError will be thrown from the int() function which will be caught by the except block and a message will be shown to the user that the input cannot be converted into integer.

print("Input String is:")
myInput= "123a"
print(myInput)
try:
    print("Output Integer is:")
    myInt=int(myInput)
    print(myInt)
except ValueError:
    print("Input cannot be converted into integer.")

Output:

Input String is:
123a
Output Integer is:
Input cannot be converted into integer.

Conclusion

In this article, we have seen why “ValueError: invalid literal for int() with base 10” occurs in python and have understood the reasons and mechanism behind it. We have also seen that this error can be avoided by first checking if the input to int() function consists of only digits or not using different methods like regular expressions and inbuilt functions. 

The post ValueError: Invalid Literal For int() With Base 10 appeared first on PythonForBeginners.com.



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...