Python computing the sum of each digit of a number
This Python program will compute the sum of each digit of an integer. For example, given input 123, the program will compute 1 + 2 + 3 = 6.
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 each character can be iterated.int(digit)Converts each character back to an integer.sum(...)Computes the sum of all digits.- In the example, we computed the sum of the digits of the number 12345.
Output result:
The sum of digits of 12345 is 15
Python3 Examples