4/15 works, but should it?


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#

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


#2

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?


#3

Thanks for reply.
I did it both ways


#4

So your question is answered?