This is one of my favorite sections, there are two major ways to do this.
- Convert to a string to be able to loop over
- Use floor division and modulus division to get the sum of digits
Here are the examples,
return sum([int(digit) for digit in str(number)])
Way: 2 Python 3.* for 2.* use one
def digit_sum(number, total=0):
return total if not number else (digit_sum((number // 10), (total + number % 10)))
Regarding your code, just change it to the following. You have some extra steps in that are not needed.
d = 0
for x in str(n):
d += int(x)
As you can see I just preform the conversion directly in the loop and then I convert it back into an int as it loops over the str of digits.