Python Calculate the Sum of Digits of a Number

Document 对象参考手册Python3 Examples

This Python program will calculate the sum of the digits of an integer. For example, input 123, and the program will calculate 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_sumThe function accepts an integernumberas a parameter.
  2. str(number)Convert the integer to a string so that each character can be iterated over.
  3. int(digit)Convert each character back to an integer.
  4. sum(...)Calculate the sum of all digits.
  5. In the example, we calculated the sum of the digits of the number 12345.

Output result:

The sum of digits of 12345 is 15

Document 对象参考手册Python3 Examples

Other Extensions