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



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


That's awesome, thank you!


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