Python int object is not subscriptable что за ошибка

от admin

TypeError: 'int' object is not subscriptable [Solved Python Error]

Kolade Chris

TypeError: 'int' object is not subscriptable [Solved Python Error]

The Python error «TypeError: ‘int’ object is not subscriptable» occurs when you try to treat an integer like a subscriptable object.

In Python, a subscriptable object is one you can “subscript” or iterate over.

Why the «TypeError: ‘int’ object is not subscriptable Error» Occurs

You can iterate over a string, list, tuple, or even dictionary. But it is not possible to iterate over an integer or set of numbers.

So, if you get this error, it means you’re trying to iterate over an integer or you’re treating an integer as an array.

In the example below, I wrote the date of birth ( dob variable) in the ddmmyy format. I tried to get the month of birth but it didn’t work. It threw the error “TypeError: ‘int’ object is not subscriptable”:

How to Fix the «TypeError: ‘int’ object is not subscriptable» Error

To fix this error, you need to convert the integer to an iterable data type, for example, a string.

And if you’re getting the error because you converted something to an integer, then you need to change it back to what it was. For example, a string, tuple, list, and so on.

In the code that threw the error above, I was able to get it to work by converting the dob variable to a string:

If you’re getting the error after converting something to an integer, it means you need to convert it back to string or leave it as it is.

In the example below, I wrote a Python program that prints the date of birth in the ddmmyy format. But it returns an error:

Looking through the code, I remembered that input returns a string, so I don’t need to convert the result of the user’s date of birth input to an integer. That fixes the error:

Conclusion

In this article, you learned what causes the «TypeError: ‘int’ object is not subscriptable» error in Python and how to fix it.

If you are getting this error, it means you’re treating an integer as iterable data. Integers are not iterable, so you need to use a different data type or convert the integer to an iterable data type.

And if the error occurs because you’ve converted something to an integer, then you need to change it back to that iterable data type.

Error: 'int' object is not subscriptable — Python

I was trying a simple piece of code, get someone’s name and age and let him/her know when they turn 21. not considering negatives and all that, just random.

I keep getting this ‘int’ object is not subscriptable error.

Prateek Gupta's user avatar

10 Answers 10

When you type x = 0 that is creating a new int variable (name) and assigning a zero to it.

When you type x[age1] that is trying to access the age1 ‘th entry, as if x were an array.

Jonathon Reinhart's user avatar

The problem is in the line,

What you want is

You also need to convert the int to a string for the output.

The complete script looks like,

‘int’ object is not subscriptable is TypeError in Python. To better understand how this error occurs, let us consider the following example:

If we run the code, you will receive the same TypeError in Python3.

Here the index of the list is out of range. If the code was modified to:

The output will be 1(as indexing in Python Lists starts at zero), as now the index of the list is in range.

When the code(given alongside the question) is run, the TypeError occurs and it points to line 4 of the code :

The intention may have been to create a list of an integer number(although creating a list for a single number was not at all required). What was required was that to just assign the input(which in turn converted to integer) to a variable.

Как решить TypeError: объект ‘int’ не поддается подписке

TypeError: ‘int’ object is not subscriptable ошибка возникает, когда вы пытаетесь рассматривать interger как подписываемый объект, такой как String, list и т. Д.

  • Автор записи

Как решить TypeError: объект ‘int’ не поддается подписке

Вступление

Некоторые объекты в python являются подписными. Это означает, что они удерживают и удерживают другие объекты, но целое число не является объектом с подпиской. Мы используем целые числа, используемые для хранения целых числовых значений в python. Если мы рассматриваем целое число как объект с возможностью подписки, оно вызовет ошибку. Итак, мы будем обсуждать конкретный тип ошибки, которую мы получаем при написании кода на python, то есть TypeError: объект ‘int’ не является подписываемым. Мы также обсудим различные методы преодоления этой ошибки.

Что такое TypeError: объект ‘int’ не поддается подписке?

Что такое TypeError?

Ошибка TypeError возникает при попытке оперировать значением, которое не поддерживает эту операцию. Давайте разберемся с помощью примера:

Читать:
Me fo что это за программа

Предположим, мы попытаемся объединить строку и целое число с помощью оператора ‘+’. Здесь мы увидим TypeError, поскольку операция + не разрешена между двумя объектами разных типов.

Объяснение:

Здесь мы взяли строку “Литеральные решения” и взяли число. После этого в операторе печати мы попытаемся добавить их. В результате: произошла ошибка типа.

Что такое объект ‘int’, не поддающийся подписке?

Когда мы пытаемся объединить строковые и целочисленные значения, это сообщение говорит нам, что мы рассматриваем целое число как подписываемый объект. Целое число не является подписываемым объектом. Объекты, содержащие другие объекты или типы данных, такие как строки, списки, кортежи и словари, могут быть подписаны. Давайте возьмем пример:

1. Number: typeerror: Объект ‘int’ не поддается подписке

Объяснение:

Здесь мы взяли число и попытались напечатать сквозное индексирование, но оно показывает typeerror, так как целые числа не поддаются подписке.

2. List: typeerror: объект ‘int’ не является подписываемым

Эта проблема Typeerror не возникает в списке, так как это подписываемый объект. Мы можем легко выполнять такие операции, как нарезка и индексация.

Объяснение:

Здесь, во-первых, мы взяли список имен и получили к нему доступ с помощью индексации. Таким образом, он показывает результат в виде решений.

Повседневный Пример Того, Как может Произойти typeerror: ‘int’ объект не является подписываемым

Давайте возьмем простой и повседневный пример вашей даты рождения, записанной в дате, месяце и году. Мы напишем программу, которая возьмет ввод пользователя и распечатает дату, месяц и год отдельно.

Объяснение:

Здесь, во-первых, мы взяли программу для печати даты рождения отдельно с помощью индексации. Во-вторых, мы взяли целочисленные входные данные даты рождения в виде даты, месяца и года. В-третьих, мы разделили дату, месяц и год с помощью индексации, а после этого печатаем их отдельно, но получаем вывод ad TypeError: объект ‘int’ не поддается подписке. Как мы изучали выше, объект integer не является подписываемым.

Решение TypeError: объект ‘int’ не является подписываемым

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

Чтобы решить эту проблему сейчас, мы удалим оператор int() из нашего кода и запустим тот же код.

Объяснение:

Здесь мы только что взяли входные данные в строку, просто удалив int(), и теперь мы можем сделать индексацию и href=”https://docs.python.org/2.3/whatsnew/section-slices.html”>нарезать в нем легко, так как он стал списком, который можно подписывать, так что никакой ошибки не возникает. href=”https://docs.python.org/2.3/whatsnew/section-slices.html”>нарезать в нем легко, так как он стал списком, который можно подписывать, так что никакой ошибки не возникает.

Должен Читать

    [Решено] TypeError: Только Массивы Размера 1 Могут Быть Преобразованы В Скаляры Python Error 50+ Часто Задаваемых Вопросов Python Для Интервью Python Max Int | Каково максимальное значение типа данных int в Python Python int to Binary | Integer to Binary Преобразование Недопустимый литерал для int() с базой 10 | Ошибка и разрешение

Вывод: Typeerror: объект ‘int’ не поддается подписке

Мы узнали все ключевые моменты о TypeError: объект ‘int’ не поддается подписке. Существуют такие объекты, как список, кортеж, строки и словари, которые могут быть подписаны. Эта ошибка возникает при попытке выполнить индексацию или нарезку целого числа.

Предположим, нам нужно выполнить такие операции, как индексация и нарезка целых чисел. Во-первых, мы должны преобразовать целое число в строку, список, кортеж или словарь.

Теперь вы можете легко решить этот python TypeError, как smartcode.

Однако, если у вас есть какие-либо сомнения или вопросы, дайте мне знать в разделе комментариев ниже. Я постараюсь помочь вам как можно скорее.

TypeError: ‘int’ object is not subscriptable

Python TypeError: ‘int’ object is not subscriptable

This error occurs when you try to use the integer type value as an array.

In simple terms, this error occurs when your program has a variable that is treated as an array by your function, but actually, that variable is an integer.

Example 1) Error Code

In the above program as you can see we have declared an integer variable ‘productPrice’ and in the next line, we are trying to print the value of integer variable productPrice[0] as a list.

Correct code

Example 2: Error Code

In the example above, we have assigned an integer value to variable ‘productPrice’, but in print statement, we are trying to use it as an array.

Solution

To resolve this error, you need to avoid using integer type values as an array.

Correct code:

How to avoid this Error

You can avoid this error if you keep the following points in your mind:

Похожие статьи