Why do I get "TypeError: 'int' object is not iterable" when trying to sum digits of a number? [duplicate]
Asked Answered
T

4

101

Here's my code:

import math

print("Hey, lets solve Task 4 :)")

number1 = input("How many digits do you want to look at? ")
number2 = input("What would you like the digits to add up to? ")

if number1 == 1:
    cow = range(0,10)
elif number1 == 2:
    cow = range(10,100)
elif number1 == 3:
    cow = range(100,1000)
elif number1 == 4:
    cow = range(1000,10000)
elif number1 == 5:
    cow = range(10000,100000)
elif number1 == 6:
    cow = range(100000,1000000)
elif number1 == 7:
    cow = range(1000000,10000000)
elif number1 == 8:
    cow = range(10000000,100000000)
elif number1 == 9:
    cow = range(100000000,1000000000)
elif number1 == 10:
    cow = range(1000000000,10000000000)

number3 = cow[-1] + 1

n = 0
while n < number3:
    number4 = list(cow[n])
    n += 1

I am looking to make a loop so that for each element in the list, it will get broken down into each of it's characters. For example, say the number 137 was in the list then it would be turned into [1,3,7]. Then I want to add these numbers together (I haven't started that bit yet but I have some idea of how to do it).

However, I keep getting this error message:

TypeError: 'int' object is not iterable

What am I doing wrong?

Tyra answered 22/10, 2013 at 16:37 Comment(4)
What do you expect list(cow[n]) to do ?Utricle
Hint: you can give range() dynamic arguments too: cow = range(10 ** (number1 - 1) if number1 > 1 else 0, 10 ** number1) would give you the exact same results as all your if statements, in just one line.Intangible
@MartijnPieters I was just thinking about that - but think IIRC, 10 ** 0 is 1 not 0Utricle
@JonClements: adjusted. :-) That 0 is quite inconsistent in this case; all the other numbers are powers of 10..Intangible
P
133

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>
Penance answered 22/10, 2013 at 16:40 Comment(5)
Thanks for answering so quickly. How would I then split the number up into individual characters? I tried putting a list(number4) beneath it but that then causes it to run forever when I run it on terminal.Tyra
Integers don't have characters. However, you could convert it to a string, which does: str(..). You might not need to convert it to a list after that, depending on what you intend to do with it, because strings are iterable and yield their constituent characters.Agglutinative
@Mikey6743 - See my edit. While you could use a for-loop for this, the quickest option is to use sum.Penance
This is great guys, thank you so much! I've just started learning how to code :) I'm still confused on how to repeat get this to repeat without using a loop. For example, say the user want's to look at 3 digits then I must work it out from 100 to 999. E.g. sum of the integers in 100 = 1 and sum of the integers in 999 = 27.Tyra
@Mikey6743 - Hmm, then you might have to use a loop. However, since the topic of this question was the TypeError (which my post fixes), why not first close this question as answered (click the tick next to my answer) and then ask another question that focuses on that problem in particular? You'll get better help that way. You definitely have to make the number a string first though so that you can split it into digits.Penance
U
11

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- int object is not iterable

Use -> for i in range(0,n):works fine..!

Unfrock answered 30/12, 2020 at 20:22 Comment(0)
H
3

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 
Harassed answered 29/12, 2018 at 23:19 Comment(0)
B
0
def hourglassSum(arr):
    sum1 = []
    # Write your code here
    for i in range(0,len(arr)-2):
        for j in range(0,len(arr)-2):
            x = sum(arr[i][j]+arr[i+1][j+1]+arr[i+2][j]+arr[i][j+1]+arr[i][j+2]+arr[i+2][j+1]+arr[i+2][j+2])
            sum1.append(x)
            #sum1.append(arr[i][j]+arr[i][j+1]+arr[i][j+2]+arr[i+1][j+1]+arr[i+2][j]+arr[i+2][j+1]+arr[i+2][j+2])
    return max(sum1)

# Why x = sum(arr[i][j]+arr[i+1][j+1]+arr[i+2][j]+arr[i][j+1]+arr[i][j+2]+arr[i+2][j+1]+arr[i+2][j+2]) is showing TypeError: 'int' object is not iterable

and if we run the comment statement below the statement than it runs properly..

Bambara answered 26/7, 2021 at 6:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.