8. Loops: Practise Makes Perfect: 4. digit_sum


#1



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):
    str(n)
    for x in n:
        return sum(int(x))


#2

problem1.
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.


#3

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:
        int(x)
        ls.append(x)
        sum(ls)
        return ls

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

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


#4

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
    int(n)
    for x in n:
        c += n
        return c

hint**
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..

1
2
3
4

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!


#5

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


#6

You finally solved it! :thumbsup:
cheers!!

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


#7

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