Just as a note you do not need to include the
. The sum function automagically iterates over what you give it including a generator.
sum(int(x) for x in str(n))
If you would like a solution that preforms the solution you have but as one line.
def digit_sum(number, total=0):
return total if number <= 0 else digit_sum(number // 10, total+(number % 10))
The above uses recursion to complete the task.
You could also do it as an anonymous function aka a lambda.
digit_sum = lambda number, total=0: total if number <= 0 else digit_sum(number // 10, total+(number % 10))
Although in this case I would refrain from using the lambda as it makes it harder to read, but it is nice you can change things around and still get the same result.
Also the number to string then back to int can be done as a lambda as well.
digit_sum = lambda number: sum(int(num) for num in str(number))
All in all there are many solutions, you just have to use your best judgement for that particular problem.