# 4. digit_sum

#1

Oops, try again. Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "'int' object is not iterable" error.

I thought I have made my argument positive: x > 0

``````def digit_sum(n):
for x in n:
x > 0 and type(x) == int
n += x
return n``````

#2

you have to first convert n to strng , so that you can add the digits, which is the goal of this excercise.

#3

I've tried this:

def digit_sum(n):
for x in n:
n = str(n)
x > 0 and type(x) == int
n += x
return n

It still returns an error.

#4

here:

``for x in n:``

`n` is still a integer, integers aren't iterable (can't be looped over)

that is why you need the string conversion, your string conversion is done too late

#5

Ok, now I get this part. Currently my code is as follows:

``````def digit_sum(n):
n = str(n)
for x in n:
x > 0 and type(x) == int
n += x
return n``````

and it gives the error:
Oops, try again. Your function fails on digit_sum(434). It returns 434434 when it should return 11.

#6

this line:

``x > 0 and type(x) == int``

it doesn't do anything, given there is no `if` keyword, even if there was, its not relevant, `x` is a string

You need to to convert to integer before adding to total, speaking of total, total is missing? You just add to `n` which already contains 434, why?

#9

Thanks for help, but instead of trying to fix it i wrote it anew. I couldn't follow the logic which led me there in the first place :). That is what worked eventually:
def digit_sum(n):
n = str(n)
suma = 0
for x in n:
suma += int(x)
return suma

#10

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.