Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python computing the sum of each digit of a number

Python computing the sum of each digit of a number

Document Object Reference Manual Python3 Examples

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

)

print

(

f

"The sum of digits of {number} is {result}"

)

Code analysis:

  1. digit_sum The function takes an integer number as its argument.
  2. str(number) Converts the integer to a string so that each character can be iterated.
  3. int(digit) Converts each character back to an integer.
  4. sum(...) Computes the sum of all digits.
  5. In the example, we computed the sum of the digits of the number 12345.

Output result:

The sum of digits of 12345 is 15

Document Object Reference Manual Python3 Examples