Python computing the sum of digits of a given number
We can compute the sum of the digits of a given number by converting it to a string, then iterating over each character in the string, converting it back to an integer, and accumulating the sum.
Example
def
digit_sum
(
number
)
:
return
sum
(
int
(
digit
)
for
digit
in
str
(
number
)
)
Example usage
number
=
12345
result
=
digit_sum
(
number
)
(
f
"The sum of digits of {number} is {result}"
)
Code analysis:
digit_sumThe function takes an integernumberas its argument.str(number)Converts the integer to a string so that it can be iterated character by character.int(digit) for digit in str(number)is a generator expression that converts each character in the string back to an integer.sum(...)The function sums these integers to obtain the sum of the digits.- Finally, we use
printfunction to output the result.
Output result:
The sum of digits of 12345 is 15
Python3 Examples