Python 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 an 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. Let us know about “Python ValueError: Invalid Literal For int() With Base 10”

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

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 the 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 an 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 the first argument and an optional argument base which denotes the number format. The base has a default value of 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 the base will always be zero.  We can understand it from the following examples.

Example 1:

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. 

CodeOutput
print(“Input Floating point number is”)myInput= 11.1print(myInput)print(“Output Integer is:”)myInt=int(myInput)print(myInt)Input Floating point number is11.1Output Integer is:11

Example 2:

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. 

CodeOutput
print(“Input String is:”)myInput= “123”print(myInput)print(“Output Integer is:”)myInt=int(myInput)print(myInt)Input String is:123Output 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 exception can occur in the following four 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.We can understand this point using the following example

Example 3:

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.

CodeOutput
print(“Input String is:”)myInput= “123b”print(myInput)print(“Output Integer is:”)myInt=int(myInput)print(myInt)Input String is:123bOutput 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: ‘123b’
  1. 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.

Example 4:

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.

CodeOutput
print(“Input String is:”)myInput= “1 2 3″print(myInput)print(“Output Integer is:”)myInt=int(myInput)print(myInt)Input String is:1 2 3Output 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: ‘1 2 3’
  1. 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.

Example 5:

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.

CodeOutput
print(“Input String is:”)myInput= “1.24”print(myInput)print(“Output Integer is:”)myInt=int(myInput)print(myInt)Input String is:1.24Output 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: ‘1.24’

How To Remove “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 is 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.

Example 6:

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.

CodeOutput

import reprint(“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.”)
Input String is:123Output 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.

Example 7:

CodeOutput
import reprint(“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.”)    
Input String is:123aInput Cannot be converted into Integer.
  1. 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.

Example 8:

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.

CodeOutput
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.”)Input String is:123Output 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.

Example 9:

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.

CodeOutput

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.”)
Input String is:123aInput cannot be converted into integer.
  1. 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.

Example 10:

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. 

CodeOutput
import reprint(“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(“The input is not a valid floating point literal.”)Input String is:1234.5Output 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.

.

Example 11:

CodeOutput
import reprint(“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(“The input is not a valid floating point literal.”)Input String is:1234aThe input is not a valid floating point literal.
  1. We can also use exception handling in python 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.

Example 12:

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

CodeOutput
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.”)Input String is:123Output 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.

Example 13:

CodeOutput
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.”)Input String is:123aOutput 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. 

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top