Reputation: 31
Im getting the error:
>>> sum_digits(123)
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
sum_digits(123)
File "D:/Python/Final/#4.py", line 4, in sum_digits
for i in n:
TypeError: 'int' object is not iterable
>>>
def sum_digits(n):
s = 0
for i in n:
s += n
return s
Upvotes: 2
Views: 363
Reputation: 180401
You cannot iterate over an int but you can still do it without casting to str
:
def sum_digits(n):
n, i = divmod(n, 10)
while n:
n, r = divmod(n, 10)
i += r
return i
Demo:
In [2]: sum_digits(123456789)
Out[2]: 45
In [3]: sum_digits(123)
Out[3]: 6
In [4]: sum_digits(100)
Out[4]: 1
It does not make much sense to convert from int to str then back to int again.
Upvotes: 0
Reputation: 78690
The problem here is that your are passing an int
to your function, which you cannot iterate over.
I suggest the solution
>>> n = 123
>>> sum(int(x) for x in str(n))
6
Upvotes: 2
Reputation: 49803
If you want i
to range over the digits of n
, you'd need something like:
for i in [int(x) for x in str(n)]:
Or, you could just pass "123"
instead of 123
to sum_digits
, which the title of your post suggests is what you actually mean to do. Of course, then you'd need to convert each character to its numeric value.
Upvotes: 0
Reputation: 369064
You need to convert the number to str
(not int
) and iterate it:
def sum_digits(n):
s = 0
for i in str(n):
s += int(i)
return s
usage:
>>> sum_digits(123)
6
Using sum
and generator expression:
def sum_digits(n):
return sum(int(i) for i in str(n))
# OR return sum(map(int, str(n)))
Upvotes: 2