We all are so clever!


#1

We all are so clever!)))

Look at my ■■■■-code.

def digit_sum(n):
    if n<0:
        return False
    else:
        total=len(str(n))
        b=0
        while total>0:
            a=n%10
            print a
            b=b+a
            n=n//10
            total -=1
        else:
            print b
            return b
digit_sum(434)

Digit_sum need help with it all
#2

But this doesn't work.Throws a "local variable "total" referenced before assignment" error.


#3

both this:

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

and this:

total = 0
for x in str(n):
    total += int(x)
return total

work fine, if you have a problem with the exercise, please make a new topic so someone can help you


#4

Yes the first one does work fine, should have clarified. The second, however, does not.


#5

yea, because the function is missing, the second one is only the function content.


#6

I get that but even then it throws the error. I ended up creating the list instead so I solved the actual problem, just wanted to point out that that doesn't seem to work for me.


#7

works perfectly fine:

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

#8

You have the right idea but the application is a little off.

total = 0
while n > 0:
    total += n % 10
    n //= 10
return total

#9

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