Python Calculate the Sum of Digits of a Number
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}")
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:
digit_sumThe function accepts an integernumberas a parameter.str(number)Convert the integer to a string so that each character can be iterated over.int(digit)Convert each character back to an integer.sum(...)Calculate the sum of all digits.- In the example, we calculated the sum of the digits of the number 12345.
Output result:
The sum of digits of 12345 is 15Other Extensions
Python3 Examples