Digit_sum try to get complicated way


#1

Your function fails on digit_sum(434). It returns 12 when it should return 11.

Hi all,
I have done it in normal way with Str() and it works, but i checked the hint and i want to try it with modulo and floor division, but seems that there is a problem (434 returns 12 instead of 11) but i don't know where,I think is something about the modulo and floor division operations. Can pls someone help?
here is the code:


def digit_sum(n):
    numero=0
    for num in str(n):
        numero += n%10
        n // 10
    return numero


#2

well first off, you still use str()? you shouldn't, since you don't want to.

this:

n // 10

won't update n, // simply means floor division, maybe rethink how you do this?


#3

Lol i forgot to assign the operation to 'n' That was really stupid. And works better with 'while' loop thanks for help and fast answer :slight_smile:


#4

yes you did.

Yea, a while loop would be a better loop for this approach.

You solved it the complicated way? well done!


#5

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