Typeerror int object is not iterable python 3 как исправить
Перейти к содержимому

Typeerror int object is not iterable python 3 как исправить

  • автор:

How to Fix TypeError: Int Object Is Not Iterable in Python

How to Fix TypeError: Int Object Is Not Iterable in Python

The Python TypeError: ‘int’ object is not iterable is an exception that occurs when trying to loop through an integer value. In Python, looping through an object requires the object to be “iterable”. Since integers are not iterable objects, looping over an integer raises the TypeError: ‘int’ object is not iterable exception.

Python TypeError: Int Object Is Not Iterable Example

Here’s an example of a Python TypeError: ‘int’ object is not iterable thrown when trying iterate over an integer value:

myint = 10 for i in myint: print(i) 

In the above example, myint is attempted to be iterated over. Since myint is an integer and not an iterable object, iterating over it raises a TypeError: ‘int’ object is not iterable :

File "test.py", line 3, in for i in myint: TypeError: 'int' object is not iterable 

How to Fix TypeError: Int Object Is Not Iterable

In the above example, myint cannot be iterated over since it is an integer value. The Python range() function can be used here to get an iterable object that contains a sequence of numbers starting from 0 and stopping before the specified number.

Updating the above example to use the range() function in the for loop fixes the error:

myint = 10 for i in range(myint): print(i) 

Running the above code produces the following output as expected:

0 1 2 3 4 5 6 7 8 9 

How to Avoid TypeError: Int Object Is Not Iterable

The Python TypeError: ‘int’ object is not iterable error can be avoided by checking if a value is an integer or not before iterating over it.

Using the above approach, a check can be added to the earlier example:

myint = 10 if isinstance(myint, int): print("Cannot iterate over an integer") else: for i in myint: print(i) 

A try-except block can also be used to catch and handle the error if the type of object not known beforehand:

myint = 10 try: for i in myint: print(i) except TypeError: print("Object must be an iterable") 

Surrounding the code in try-except blocks like the above allows the program to continue execution after the exception is encountered:

Object must be an iterable 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

TypeError: ‘int’ object is not iterable

TypeError: cannot unpack non-iterable int object
Добрый день Вот код# -*- coding: utf-8 -*- """ This Example will show you how to use.

Ошибка ‘int’ object is not iterable
Программа должна сортировать элементы списка по неубыванию произведений цифр числа. На выходе.

TypeError: ‘int’ object is not callable
Начал изучать питон но столкнулся с проблемой. def d(): x=int(input("Введите: ")).

TypeError: ‘int’ object is not subscriptable
a = b = n = int ( input()) n-=1 for i in range ( 0 , n ): a = int (input()) b = int.

TypeError: ‘int’ object is not subscriptable
i = l = z = 0 dlina = 0 for l in l: dlina=dlina+l*2 z=z+1 print(dlina, z) .

4974 / 3210 / 1125
Регистрация: 21.03.2016
Сообщений: 7,940

a = 150
какое максимальное или минимальное вы хотите из этого получить? это раз!
ошибка вам говорит что число не итерабельный тип данных. — это два!
читать основы нужно!

307 / 188 / 97
Регистрация: 01.05.2014
Сообщений: 519

a, b, c = map(int, input().split()) print((a + b + c) - max(a, b, c) - min(a, b, c))

4974 / 3210 / 1125
Регистрация: 21.03.2016
Сообщений: 7,940

print(sorted(map(int, input().split()))[1])

87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
Помогаю со студенческими работами здесь

TypeError: ‘int’ object is not callable
Здравствуйте, интересует такой вопросик(вот код): def Fs(t,c,T): t0=c global Fs .

TypeError: ‘int’ object is not subscriptable
a = int(input()) lat = lst = for i in range(a): lst.append(i) if int(i) >= 4: .

Ошибка TypeError: ‘int’ object is not subscriptable
b = ]]]] print(a) Вот сам код не понимаю почему выходит ошибка

Ошибка TypeError: ‘int’ object is not subscriptable
Здравствуйте. Решаю следующую задачу: Дан набор из N целых положительных чисел. Для каждого числа.

How to Fix the Python TypeError: ‘int’ Object is not Iterable

The Python TypeError: ‘int’ object is not iterable is a common error that occurs when you try to iterate over an integer object in Python. This error occurs because the int type in Python is not iterable, and you cannot use a for loop to iterate over it. In this article, we will take a look at what causes this error and how to fix it.

What Causes the TypeError: ‘int’ Object is not Iterable?

The TypeError: ‘int’ object is not iterable occurs when you try to use a for loop to iterate over an integer object in Python. For example, the following code will cause this error:

num = 5
for i in num:
print(i)

This error occurs because the int type in Python is not iterable. In other words, you cannot use a for loop to iterate over an integer object in Python. Instead, you need to use a while loop or other looping construct.

How to Fix the TypeError: ‘int’ Object is not Iterable

There are several ways to fix the TypeError: ‘int’ object is not iterable. One way is to use a while loop to iterate over the integer object. For example, the following code will work:

num = 5
i = 0
while i < num:
print(i)
i += 1

Another way to fix this error is to convert the integer object to a different data type that is iterable, such as a list or a string. For example, the following code will work:

num = 5
for i in str(num):
print(i)

Additionally, you can use range() function to get a range of numbers and use for loop to iterate over that range.

num = 5
for i in range(num):
print(i)

In conclusion, the Python TypeError: ‘int’ object is not iterable is a common error that occurs when you try to iterate over an integer object in Python. This error occurs because the int type in Python is not iterable. To fix this error, you can use a while loop or convert the integer object to a different data type that is iterable, such as a list or a string. You can also use the range() function to get a range of numbers and use a for loop to iterate over that range.

It is important to keep in mind that the best solution will depend on the specific context of your code and what you are trying to achieve. When encountering this error, you should carefully consider your options and choose the solution that best fits your needs.

Furthermore, it’s important to always pay attention to the types of the variables you are working with in Python, and to understand the behavior of the different data types and their methods. This will help you avoid common errors like the TypeError: ‘int’ object is not iterable and make your code more robust and efficient.

In any case, understanding the cause of this error and knowing how to fix it is an essential step for any Python developer, and will allow you to write more efficient and effective code.

Работа с ошибками в Python

Наш код подразумевает печать содержимого переменной vector.

Запустим написанный скрипт, получим следующий вывод:

$ python3 solution.py Traceback (most recent call last): File "solution.py", line 1, in for coord in vector: NameError: name 'vector' is not defined 

Сообщение означает, что при исполнении кода возникла ошибка. При этом Python сообщает нам кое-что ещё. Разберём это сообщение детально.

Чтение Traceback 1

Исходное сообщение нужно мысленно разделить на две части. Первая часть это traceback-сообщение:

Traceback (most recent call last): File "solution.py", line 1, in for coord in vector:

Вторая часть — сообщение о возникшей ошибке:

NameError: name 'vector' is not defined

Разберём первую часть. Traceback в грубом переводе означает «отследить назад». Traceback показывает последовательность/стэк вызовов, которая, в конечном итоге, вызвала ошибку.

Traceback (most recent call last):

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

Вторая и третья строки:

File "solution.py", line 1, in for coord in vector:

показывают информацию о вызове (в нашем случае он один). Во-первых, здесь есть информация о файле, в котором произошёл вызов («solution.py»), затем указан номер строки, где этот вызов происходит («line 1»), в конце стоит информация о том, откуда произошёл вызов («»). В нашем случае вызов происходит непосредственно из модуля, т.е. не из функции. Наконец, вывод содержит не только номер строки, но и саму строку «for coord in vector:».

Заключительная строка сообщения:

NameError: name 'vector' is not defined

содержит вид (тип) ошибки («NameError»), и после двоеточия содержит подсказку. В данном случае она означает, что имя «vector» не определено.

В самом деле, если взглянуть снова на код, то можно убедиться, что мы нигде не объявили переменную «vector».

Подведём итоги. При попытке запуска мы получили следующий вывод

$ python3 solution.py Traceback (most recent call last): File "solution.py", line 1, in for coord in vector: NameError: name 'vector' is not defined 

Он говорит нам о возникновении ошибки. Эта ошибка обнаружилась интерпретатором в первой строке файла «solution.py». Сама ошибка является ошибкой имени и указывает на необъявленное имя — «vector».

Чтение Traceback 2

Оберните код из solution.py в функцию:

1 2 3 4 5
def print_vector(vector): for coord in vector: print(coord) print_vector(5) 

Запустим наш код

$ python3 solution.py Traceback (most recent call last): File "solution.py", line 5, in print_vector(5) File "solution.py", line 2, in print_vector for coord in vector: TypeError: 'int' object is not iterable 

На этот раз сообщение об ошибке сложнее, однако структура у него та же.

Часть со стеком вызовов увеличилась:

Traceback (most recent call last): File "solution.py", line 5, in print_vector(5) File "solution.py", line 2, in print_vector for coord in vector:

Поскольку «most recent call last», читать будем её сверху вниз.

Вызовов на этот раз два. Первый вызов:

File "solution.py", line 5, in print_vector(5)

Произошел в пятой строке. Судя по строчке кода, это вызов написанной нами функции print_vector(5) с аргументом 5.

Следом за ней второй вызов:

File "solution.py", line 2, in print_vector for coord in vector:

Этот вызов происходит внутри функции print_vector, содержащейся в файле «solution.py». Вызов находится в строке 2.

Сама же ошибка имеет вид:

TypeError: 'int' object is not iterable

Как и в первом примере, сообщение об ошибке содержит её тип и подсказку. В нашем случае произошла ошибка типа. В подсказке же указано, что объект типа int не является итерируемым, т.е. таким объектом, который нельзя использовать в цикле for.

$ python3 solution.py Traceback (most recent call last): File "solution.py", line 5, in print_vector(5) File "solution.py", line 2, in print_vector for coord in vector: TypeError: 'int' object is not iterable 

В нашем коде возникла ошибка. Её вызвала последовательность вызовов. Первый вызов произошел непосредственно из модуля — в строке 5 происходит вызов функции print_vector(5). Внутри этой функции ошибка возникла в строчке 2, содержащей проход по циклу. Сообщение об ошибке означает, что итерироваться по объекту типа int нельзя. В нашем случае мы вызвали функцию print_vector от числа (от 5).

Некоторые ошибки с примерами кода

Ошибки в синтаксисе

Наиболее частая ошибка, которая возникает в программах на Python — SyntaxError: когда какое-то утверждение записано не по правилам языка, например:

$ python3 >>> print "hello" File "", line 1 print "hello" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")? 

Тот же тип ошибки возникнет, если забыть поставить двоеточие в цикле:

$ python3 >>> for i in range(5) File "", line 1 for i in range(5) ^ SyntaxError: invalid syntax 

При неправильном использовании пробелов и табуляций в начале строки возникает IndentationError:

$ python3 >>> for i in range(5): print(i) File "", line 2 print(i) ^ IndentationError: expected an indented block 

А теперь посмотрим, что будет, если в первой строке цикла воспользоваться пробелами, а во второй — табуляцией:

$ python3 >>> for i in range(5): print(i) # здесь пробелы print(i**2) # здесь табуляция File "", line 3 print(i**2) ^ TabError: inconsistent use of tabs and spaces in indentation 

NameError возникает при обращении к несуществующей переменной:

$ python3 >>> words = "Hello" >>> word Traceback (most recent call last): File "", line 1, in NameError: name 'word' is not defined 

Ошибки в логике

Напишем простую программу на деление с остатком и сохраним как sample.py:

n = input() m = input() print(n % m) 
$ python3 sample.py 5 3 Traceback (most recent call last): File "sample.py", line 3, in print(n % m) TypeError: not all arguments converted during string formatting 

Возникла ошибка TypeError, которая сообщает о неподходящем типе данных. Исправим программу:

n = int(input()) m = int(input()) print(n % m) 

запустим на неподходящих данных:

$ python3 sample.py xyz Traceback (most recent call last): File "sample.py", line 1, in n = int(input()) ValueError: invalid literal for int() with base 10: 'xyz' 

Возникнет ValueError. Эту ошибку ещё можно воспринимать как использование значения вне области допустимых значений (ОДЗ).

Теперь запустим программу на числовых данных:

$ python3 sample.py 1 0 Traceback (most recent call last): File "sample.py", line 3, in print(n % m) ZeroDivisionError: integer division or modulo by zero 

При работе с массивами нередко возникает ошибка IndexError. Она возникает при выходе за пределы массива:

$ python3 >>> L1 = [1, 2, 3] >>> L1[3] Traceback (most recent call last): File "", line 1, in IndexError: list index out of range 

Что будет, если вызвать бесконечную рекурсию? Опишем её в программе endless.py

def noend(): print("Hello!") noend() noend() 

Через некоторое время после запуска возникнет RecursionError:

Traceback (most recent call last): File "endless.py", line 4, in noend() File "endless.py", line 3, in noend noend() File "endless.py", line 3, in noend noend() File "endless.py", line 3, in noend noend() [Previous line repeated 993 more times] File "endless.py", line 2, in noend print("Hello!") RecursionError: maximum recursion depth exceeded while calling a Python object 

Контест на повторение

  • Начинающие (участвовать)
  • Основные (участвовать)
  • Продвинутые (участвовать)

Сайт построен с использованием Pelican. За основу оформления взята тема от Smashing Magazine. Исходные тексты программ, приведённые на этом сайте, распространяются под лицензией GPLv3, все остальные материалы сайта распространяются под лицензией CC-BY.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *