4/15 works, but should it?



Hi, I`ve tried digit_sum challange, and this code works fine, but please explain me why ( I iterate through string and not changing type back to integer after for addition, why is this working fine?)

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


Well str(n) creates a stringified version of n to be used for the for loop, but that doesn't change n, you do not do n = str(n). So n is what it used to be, probably a number and with numbers you're allowed to do numerical operations.

BTW: if you already go through the number digit by digit, why not just convert to int and sum those up?


Thanks for reply.
I did it both ways


So your question is answered?