Hi, good question. If you are considering to only work with integers then you can go about using the following syntax to do it in the most efficient way possible. Check it out:
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
However, the same can be done using the divmod function as well. Check this:
def sum_digits2(n):
s = 0
while n:
n, remainder = divmod(n, 10)
s += remainder
return s
Also, wanted to tell you that whatever you have posted is perfectly right to solve the purpose. but there is a faster way to go about doing it and this is by using a version without any augmented assignments. Check it out:
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
Hope this helps!