Digit Sum



I am trying to figure out how to get the digit sum using primarily modulos and floor division... I have figured out how to get the digit sum for "less than ever factor of ten" (n<10000 sum=) but to combine it into a unified function is troubling me. Here is what I have:

def digit_sum(n):

if n<10:
    return sum
elif n<100:
    sum= (n%10)+(n//10)
    return sum
elif n<1000:
    sum = (n%10)+((n//10)%10)+((n//100)%10)
    return sum
elif n<10000:
    sum = (n%10)+((n//10)%10)+((n//100)%10)+(n//1000%10)
    return sum
elif n<100000:
    sum = (n%10)+((n//10)%10)+((n//100)%10)+(n//1000%10)+(n//10000%10)
    return sum

Obviously if I won't be able to "elif:" faster than the computer can think of large words. Does anyone know how I can code (sum+=((n//10**x)%10)


Count *=10

I dont know, help me out

Replace this line with your code.


Condense this is what I want to do


Is this what you mean by 'condense'?

def digit_sum(n):
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total


Essentially I would like to find a way to add (n//(x))%10 to the sum whenever the digit surpasses a new factor of 10.

In an example where n is 5436, and the elif condition is n<10000, x is 1000

Your version may make it easier to do this, but for the digit_sum problem what you provided only works for 2 digit numbers


digit_sum(123456789)    # 45

Will need to play around with your premise to see if I can come up with a working solution.