Digit_sum


#1



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


For digit_sum(434) my code returns 12 when it should return ll. Why is this?


def digit_sum(n):
    times = 0 
    total = 0
    
    while times < len(str(n)):   
        total = total + (n%10)
        times += 1
        n // 10
    return total


#2

here:

n // 10

you don't store the result of this division in a variable? Maybe you should store the result of this division in n, then your while loop condition can be to see if n is greater then zero, since n becomes 0 in the end

The great thing about this solution is you don't need str(), given only math is involved and no string/integer conversion, its a more efficient program


#3

That's awesome, thank you!


#4

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