8. Loops: Practise Makes Perfect: 4. digit_sum


8. Loops: Practise Makes Perfect: 4. digit_sum

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.

def digit_sum(n):
    for x in n:
        return sum(int(x))


str(n) This code does not play any significant role .

Maybe you're trying to convert number to string and loop over it?
if yes then..
sum() method does not work on int data type.

if you want to go with same approach then..
You need to create an empty list..then..
You need to append all x(after you convert them int) into an empty list then use sum() on it and return it.

Another approach can be..

creating a variable (sayc = 0)and set it to 0(at starting of your function)
then at each iteration adding (after you convert to int type) iteration variable to c.
and at last return it.


So these are my two interpretations of both ways you suggested. Both throw the same error message as in the first post...

def digit_sum(x):
    ls = []
    for n in x:
        return ls

def digit_sum(n):
    c = 0
    for x in n:
        c += n
        return c

I should have probably standardised the notation for both, sorry...confusing i know


I'll go through second approach as it does not include list and sum() (less code,clean code)..

This code have many bugs : bad indentation,iteration over int type(which is not allowed) etc

def digit_sum(n):
    c = 0
    for x in n:
        c += n
        return c

I'll give you an example...
suppose there is a number..
say x

x = 1234

now I have to print each digit of this number..
how we go about this problem?

for dig in str(x):
   print dig

It will print..


By converting number into string,we can iterate over it(as we know we can iterate over string)!
do reply if you get this concept or not!


def digit_sum(n):
    c = 0
    for x in str(n):
        c += int(x)
    return c

FINALLY!! that has taken me about an hour (in between bouldering, for the fact-checkers)..thank you


You finally solved it! :thumbsup:

ps: delete you final working code(edit it) so other users do not able to copy it. :slight_smile:


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