Python Calculate the Sum of Digits of a Given Number

Document 对象参考手册Python3 Examples

We can calculate the sum of the digits of a given number by converting the number 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 explanation:

  1. digit_sumThe function accepts an integernumberas a parameter.
  2. str(number)Convert 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 adds these integers to obtain the sum of the digits.
  5. Finally, we use theprintfunction to output the result.

Output result:

The sum of digits of 12345 is 15

Document 对象参考手册Python3 Examples

Other extensions