Ошибка invalid literal for int with base 10

I got this error from my code:

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

What does it mean? Why does it occur, and how can I fix it?

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

asked Dec 3, 2009 at 17:34

Sarah Cox's user avatar

2

The error message means that the string provided to int could not be parsed as an integer. The part at the end, after the :, shows the string that was provided.

In the case described in the question, the input was an empty string, written as ''.

Here is another example — a string that represents a floating-point value cannot be converted directly with int:

>>> int('55063.000000')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '55063.000000'

Instead, convert to float first:

>>> int(float('55063.000000'))
55063

See:https://www.geeksforgeeks.org/python-int-function/

Mig82's user avatar

Mig82

4,7563 gold badges39 silver badges63 bronze badges

answered Jan 20, 2012 at 21:49

FdoBad's user avatar

FdoBadFdoBad

8,0371 gold badge13 silver badges2 bronze badges

10

The following work fine in Python:

>>> int('5') # passing the string representation of an integer to `int`
5
>>> float('5.0') # passing the string representation of a float to `float`
5.0
>>> float('5') # passing the string representation of an integer to `float`
5.0
>>> int(5.0) # passing a float to `int`
5
>>> float(5) # passing an integer to `float`
5.0

However, passing the string representation of a float, or any other string that does not represent an integer (including, for example, an empty string like '') will cause a ValueError:

>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
>>> int('5.0')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'

To convert the string representation of a floating-point number to integer, it will work to convert to a float first, then to an integer (as explained in @katyhuff’s comment on the question):

>>> int(float('5.0'))
5

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

answered Dec 12, 2017 at 2:26

Peter's user avatar

PeterPeter

1,9831 gold badge12 silver badges9 bronze badges

10

int cannot convert an empty string to an integer. If the input string could be empty, consider either checking for this case:

if data:
    as_int = int(data)
else:
    # do something else

or using exception handling:

try:
    as_int = int(data)
except ValueError:
    # do something else

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

answered Dec 3, 2009 at 17:40

SilentGhost's user avatar

SilentGhostSilentGhost

305k66 gold badges305 silver badges292 bronze badges

5

Python will convert the number to a float. Simply calling float first then converting that to an int will work:
output = int(float(input))

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

answered Apr 23, 2019 at 3:21

Brad123's user avatar

Brad123Brad123

84710 silver badges10 bronze badges

1

This error occurs when trying to convert an empty string to an integer:

>>> int(5)
5
>>> int('5')
5
>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

answered Mar 27, 2018 at 6:59

Joish's user avatar

JoishJoish

1,42818 silver badges23 bronze badges

The reason is that you are getting an empty string or a string as an argument into int. Check if it is empty or it contains alpha characters. If it contains characters, then simply ignore that part.

Toluwalemi's user avatar

answered Jun 23, 2017 at 13:19

rajender kumar's user avatar

1

Given floatInString = '5.0', that value can be converted to int like so:

floatInInt = int(float(floatInString))

Karl Knechtel's user avatar

Karl Knechtel

61.7k11 gold badges97 silver badges147 bronze badges

answered Dec 13, 2019 at 11:12

Hrvoje's user avatar

HrvojeHrvoje

13.1k7 gold badges86 silver badges102 bronze badges

You’ve got a problem with this line:

while file_to_read != " ":

This does not find an empty string. It finds a string consisting of one space. Presumably this is not what you are looking for.

Listen to everyone else’s advice. This is not very idiomatic python code, and would be much clearer if you iterate over the file directly, but I think this problem is worth noting as well.

answered Dec 3, 2009 at 17:56

jcdyer's user avatar

jcdyerjcdyer

18.5k5 gold badges41 silver badges49 bronze badges

1

My simple workaround to this problem was wrap my code in an if statement, taking advantage of the fact that an empty string is not «truthy»:

Given either of these two inputs:

input_string = ""    # works with an empty string
input_string = "25"  # or a number inside a string

You can safely handle a blank string using this check:

if input_string:
   number = int(input_string)
else:
   number = None # (or number = 0 if you prefer)

print(number)

answered Jan 3, 2022 at 0:30

Allen Ellis's user avatar

1

I recently came across a case where none of these answers worked. I encountered CSV data where there were null bytes mixed in with the data, and those null bytes did not get stripped. So, my numeric string, after stripping, consisted of bytes like this:

x00x31x00x0dx00

To counter this, I did:

countStr = fields[3].replace('x00', '').strip()
count = int(countStr)

…where fields is a list of csv values resulting from splitting the line.

answered Jan 10, 2020 at 17:42

T. Reed's user avatar

T. ReedT. Reed

1811 silver badge9 bronze badges

1

This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input().
Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling
enter image description here

So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.

answered Nov 28, 2017 at 6:32

Amit Kumar's user avatar

Amit KumarAmit Kumar

7842 gold badges10 silver badges16 bronze badges

1

your answer is throwing errors because of this line

readings = int(readings)
  1. Here you are trying to convert a string into int type which is not base-10. you can convert a string into int only if it is base-10 otherwise it will throw ValueError, stating invalid literal for int() with base 10.

answered May 28, 2020 at 21:10

shubham's user avatar

This seems like readings is sometimes an empty string and obviously an error crops up.
You can add an extra check to your while loop before the int(readings) command like:

while readings != 0 or readings != '':
    readings = int(readings)

OneCricketeer's user avatar

OneCricketeer

176k18 gold badges130 silver badges239 bronze badges

answered Feb 12, 2020 at 5:07

Kanishk Mair's user avatar

Kanishk MairKanishk Mair

3331 gold badge4 silver badges8 bronze badges

Landed here as I had this problem but with pandas Dataframes. I had int values stored as 12345.0.

The same solution applies in pandas (I believe it would work in numpy with ndarrays as well) :

df["my_int_value"] = df["my_string_value"].astype(float).astype(int)

answered Jun 2 at 12:45

Théo Rubenach's user avatar

I am creating a program that reads a
file and if the first line of the file
is not blank, it reads the next four
lines. Calculations are performed on
those lines and then the next line is
read.

Something like this should work:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here

answered Dec 3, 2009 at 17:49

Imran's user avatar

ImranImran

86.3k23 gold badges97 silver badges131 bronze badges

Another answer in case all of the above solutions are not working for you.

My original error was similar to OP: ValueError: invalid literal for int() with base 10: ‘52,002’

I then tried the accepted answer and got this error: ValueError: could not convert string to float: ‘52,002’ —this was when I tried the int(float(variable_name))

My solution is to convert the string to a float and leave it there. I just needed to check to see if the string was a numeric value so I can handle it correctly.

try: 
   float(variable_name)
except ValueError:
   print("The value you entered was not a number, please enter a different number")

Dharman's user avatar

Dharman

30.4k22 gold badges84 silver badges132 bronze badges

answered Jun 25, 2021 at 14:17

justanotherdev2's user avatar

1

Beginner here! I am writing a simple code to count how many times an item shows up in a list (ex. count([1, 3, 1, 4, 1, 5], 1) would return 3).

This is what I originally had:

def count(sequence, item):
    s = 0
    for i in sequence:
       if int(i) == int(item):
           s += 1
    return s

Every time I submitted this code, I got

«invalid literal for int() with base 10:»

I’ve since figured out that the correct code is:

def count(sequence, item):
    s = 0
    for i in sequence:
       if **i == item**:
           s += 1
    return s

However, I’m just curious as to what that error statement means. Why can’t I just leave in int()?

На чтение 7 мин Просмотров 59.9к. Опубликовано 17.06.2021

В этой статье мы рассмотрим из-за чего возникает ошибка ValueError: Invalid Literal For int() With Base 10 и как ее исправить в Python.

Содержание

  1. Введение
  2. Описание ошибки ValueError
  3. Использование функции int()
  4. Причины возникновения ошибки
  5. Случай №1
  6. Случай №2
  7. Случай №3
  8. Как избежать ошибки?
  9. Заключение

Введение

ValueError: invalid literal for int() with base 10 — это исключение, которое может возникнуть, когда мы пытаемся преобразовать строковый литерал в целое число с помощью метода int(), а строковый литерал содержит символы, отличные от цифр. В этой статье мы попытаемся понять причины этого исключения и рассмотрим различные методы, позволяющие избежать его в наших программах.

Описание ошибки ValueError

ValueError — это исключение в Python, которое возникает, когда в метод или функцию передается аргумент с правильным типом, но неправильным значением. Первая часть сообщения, т.е. «ValueError», говорит нам о том, что возникло исключение, поскольку в качестве аргумента функции int() передано неправильное значение. Вторая часть сообщения «invalid literal for int() with base 10» говорит нам о том, что мы пытались преобразовать входные данные в целое число, но входные данные содержат символы, отличные от цифр в десятичной системе счисления.

Использование функции int()

Функция int() в Python принимает строку или число в качестве первого аргумента и необязательный аргумент base, обозначающий формат числа. По умолчанию base имеет значение 10, которое используется для десятичных чисел, но мы можем передать другое значение base, например 2 для двоичных чисел или 16 для шестнадцатеричных. В этой статье мы будем использовать функцию int() только с первым аргументом, и значение по умолчанию для base всегда будет равно нулю. Это можно увидеть в следующих примерах.

Мы можем преобразовать число с плавающей точкой в целое число, как показано в следующем примере. Когда мы преобразуем число с плавающей точкой в целое число с помощью функции int(), цифры после десятичной дроби отбрасываются из числа на выходе.

num = 22.03
print(f"Число с плавающей точкой: {num}")
num = int(num)
print(f"Целое число: {num}")

Вывод программы:

Число с плавающей точкой: 22.03
Целое число: 22

Мы можем преобразовать строку, состоящую из цифр, в целое число, как показано в следующем примере. Здесь входные данные состоят только из цифр, поэтому они будут преобразованы в целое число.

num = "22"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")

Вывод программы

Строка: 22
Целое число: 22

Два типа входных данных, показанные в двух вышеприведенных примерах, являются единственными типами входных данных, для которых функция int() работает правильно. При передаче в качестве аргументов функции int() других типов входных данных будет сгенерирован ValueError с сообщением «invalid literal for int() with base 10». Теперь мы рассмотрим различные типы входных данных, для которых в функции int() может быть сгенерирован ValueError.

Причины возникновения ошибки

Как говорилось выше, «ValueError: invalid literal for int()» может возникнуть, когда в функцию int() передается ввод с несоответствующим значением. Это может произойти в следующих случаях.

Случай №1

Python ValueError: invalid literal for int() with base 10 возникает, когда входные данные для метода int() являются буквенно-цифровыми, а не числовыми, и поэтому входные данные не могут быть преобразованы в целое число. Это можно понять на следующем примере.

В этом примере мы передаем в функцию int() строку, содержащую буквенно-цифровые символы, из-за чего возникает ValueError, выводящий на экран сообщение «ValueError: invalid literal for int() with base 10».

num = "22я"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")

Вывод программы

Строка: 22я
Traceback (most recent call last):
  File "/Users/krnlnx/Projects/Test/num.py", line 3, in <module>
    num = int(num)
ValueError: invalid literal for int() with base 10: '22я'

Случай №2

Python ValueError: invalid literal for int() with base 10 возникает, когда входные данные функции int() содержат пробельные символы, и поэтому входные данные не могут быть преобразованы в целое число. Это можно понять на следующем примере.

В этом примере мы передаем в функцию int() строку, содержащую пробел, из-за чего возникает ValueError, выводящий на экран сообщение «ValueError: invalid literal for int() with base 10».

num = "22 11"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")

Вывод программы

Строка: 22 11
Traceback (most recent call last):
  File "/Users/krnlnx/Projects/Test/num.py", line 3, in <module>
    num = int(num)
ValueError: invalid literal for int() with base 10: '22 11'

Случай №3

Python ValueError: invalid literal for int() with base 10 возникает, когда вход в функцию int() содержит какие-либо знаки препинания, такие как точка «.» или запятая «,». Поэтому входные данные не могут быть преобразованы в целое число. Это можно понять на следующем примере.

В этом примере мы передаем в функцию int() строку, содержащую символ точки «.», из-за чего возникает ValueError, выводящий сообщение «ValueError: invalid literal for int() with base 10».

num = "22.11"
print(f"Строка: {num}")
num = int(num)
print(f"Целое число: {num}")

Вывод программы

Строка: 22.11
Traceback (most recent call last):
  File "/Users/krnlnx/Projects/Test/num.py", line 3, in <module>
    num = int(num)
ValueError: invalid literal for int() with base 10: '22.11'

Как избежать ошибки?

Мы можем избежать исключения ValueError: invalid literal for int() with base 10, используя упреждающие меры для проверки того, состоит ли входной сигнал, передаваемый функции int(), только из цифр или нет. Для проверки того, состоит ли входной сигнал, передаваемый функции int(), только из цифр, можно использовать следующие способы.

  • Мы можем использовать регулярные выражения, чтобы проверить, состоит ли входной сигнал, передаваемый функции int(), только из цифр или нет. Если входные данные содержат символы, отличные от цифр, мы можем сообщить пользователю, что входные данные не могут быть преобразованы в целое число. В противном случае мы можем продолжить работу в обычном режиме.
  • Мы также можем использовать метод isdigit(), чтобы проверить, состоит ли входная строка только из цифр или нет. Метод isdigit() принимает на вход строку и возвращает True, если входная строка, переданная ему в качестве аргумента, состоит только из цифр в десятичной системе. В противном случае он возвращает False. После проверки того, состоит ли входная строка только из цифр или нет, мы можем преобразовать входные данные в целые числа.
  • Возможна ситуация, когда входная строка содержит число с плавающей точкой и имеет символ точки «.» между цифрами. Для преобразования таких входных данных в целые числа с помощью функции int() сначала проверим, содержит ли входная строка число с плавающей точкой, т.е. имеет ли она только один символ точки между цифрами или нет, используя регулярные выражения. Если да, то сначала преобразуем входные данные в число с плавающей точкой, которое можно передать функции int(), а затем выведем результат. В противном случае будет сообщено, что входные данные не могут быть преобразованы в целое число.
  • Мы также можем использовать обработку исключений, используя try except для обработки ValueError при возникновении ошибки. В блоке try мы обычно выполняем код. Когда произойдет ошибка ValueError, она будет поднята в блоке try и обработана блоком except, а пользователю будет показано соответствующее сообщение.

Заключение

В этой статье мы рассмотрели, почему в Python возникает ошибка «ValueError: invalid literal for int() with base 10», разобрались в причинах и механизме ее возникновения. Мы также увидели, что этой ошибки можно избежать, предварительно проверив, состоит ли вход в функцию int() только из цифр или нет, используя различные методы, такие как регулярные выражения и встроенные функции.

Python ValueError: invalid literal for int() with base 10

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

While using the int() function, there are some strict rules which we must follow.

This error is triggered in one of two cases:

  1. When passing a string containing anything that isn’t a number to int(). Unfortunately, integer-type objects can’t have any letters or special characters.
  2. When passing int() a string-type object which looks like a float-type (e.g., the string '56.3'). Although technically, this is an extension of the first error case, Python recognizes the special character .inside the string '56.3'.

To avoid the error, we shouldn’t pass int() any letters or special characters.

We’ll look at a specific example for each of these causes, along with how to implement a solution.

As mentioned previously, one of the most common causes of the ValueError we’ve been looking at is passing int() an argument that contains letters or special characters.

By definition, an integer is a whole number, so an integer-type object should only have numbers (+ and - are also acceptable). As a result, Python will throw an error when attempting to convert letters into an integer.

This error can frequently occur when converting user-input to an integer-type using the int() function. This problem happens because Python stores the input as a string whenever we use input().

As a result, if you’d like to do some calculations using user input, the input needs to be converted into an integer or float.

Let’s consider a basic example and create a short program that will find the sum of two values input by the user:

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

new_val = val_1 + val_2

print("nThe sum is: ", new_val)

Out:

Enter the first value:  5
Enter the second value:  3

As you can see, we received «53» instead of the correct sum, «8». We received this output because the input must be converted to integer-type to calculate the sum correctly. We have instead added two strings together through concatenation.

So, we need to convert the values to integers before summing them, like so:

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

new_val = int(val_1) + int(val_2)

print("nThe sum is: ", new_val)

Out:

Enter the first value:  5
Enter the second value:  3

We’re now getting the correct answer.

Despite working as expected, problems can occur if users start inputting values that aren’t integers.

In the example below, we have entered «Hello» as the second input:

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

new_val = int(val_1) + int(val_2)

print("nThe sum is: ", new_val)

Out:

Enter the first value:  5
Enter the second value:  Hello

Out:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-3-697a6feaa0ed> in <module>
      2 val_2 = input("Enter the second value: ")
      3 
----> 4 new_val = int(val_1) + int(val_2)
      5 
      6 print("nThe sum is: ", new_val)
ValueError: invalid literal for int() with base 10: 'Hello'

We now have an error because the value val_2 is 'Hello', which isn’t a number. We can fix this by using a simple try/except block, like in the following solution.

In this scenario, there isn’t much that can be done about users testing the limits of our program. One potential solution is adding an exception handler to catch the error and alert the user that their entry was invalid.

val_1 = input("Enter the first value: ")
val_2 = input("Enter the second value: ")

try:
    new_val = int(val_1) + int(val_2)
    print("nThe sum is: ", new_val)
except ValueError:
    print("nWhoops! One of those wasn't a whole number")

Out:

Enter the first value:  5
Enter the second value:  Hello

Out:

Whoops! One of those wasn't a whole number

Using an exception handler here, the user will receive a warning message whenever int() throws a ValueError. This solution is a common way to handle user input that will be cast to integers.

Passing int() a string-type object which looks like a float (e.g. '56.9'), will also trigger the ValueError.

In this scenario, Python detects the ., which is a special character, causing the error. For example, here’s what happens when we pass '56.3' to int() as an argument:

Out:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-4ff8ba29c4d7> in <module>
----> 1 int("56.9")

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

int() works with floats, so the simplest way to fix the error, in this case, is to convert our string to a floating-point number first. After converting the string-type to float-type, we can successfully pass our object to the int() function:

val = float("56.9")
int(val)

The main problem with this approach is that using int() on a float will cut off everything after the decimal without round to the nearest integer.

56.9 is much closer to 57 than 56, but int() has performed a simple truncation to eliminate the decimal.

For situations where you’d prefer to round floats to their closest integer, you can add an intermediate step using the round() function, like so:

val = float("56.9")
rounded_val = round(val, 0)
int(rounded_val)

Specifying zero as our second round() argument communicates to Python that we’d like to round val to zero decimal places (forming an integer). By altering the second argument, we can adjust how many decimal numbers Python should use when rounding.

As we’ve discussed, passing an argument that contains letters or special characters to the int() function causes this error to occur. Integers are whole numbers, so any string-type objects passed to int()should only contain numbers, +or -.

In cases where we’d like to convert a string-type object that looks like float (e.g. '56.3') into an integer, we will also trigger the error. The error happens due to the presence of the .character. We can easily avoid the error by converting the string to a floating-point object first, as follows:

In cases where we’d like a number to remain a decimal, we could drop the int() function altogether and use float() to make the object a float-type. Ultimately, if you’re experiencing this error, it’s a good idea to think about what’s going into the int() function and why that could be causing problems.

The error is straightforward to resolve once you get to the bottom of what’s causing the issue.

You are here: Home / Exceptions / 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.

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. 

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Понравилась статья? Поделить с друзьями:
  • Ошибка intel cpu ucode loading
  • Ошибка invalid keystore format
  • Ошибка ip адреса доменного имени
  • Ошибка intel core
  • Ошибка invalid json response