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

Python computing the sum of digits of a given number

Python computing the sum of digits of a given number

Document Object Reference Manual Python3 Examples

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

)

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 it can be iterated character by character.
  3. int(digit) for digit in str(number) is a generator expression that converts each character in the string back to an integer.
  4. sum(...) The function sums these integers to obtain the sum of the digits.
  5. Finally, we use print function to output the result.

Output result:

The sum of digits of 12345 is 15

Document Object Reference Manual Python3 Examples