Python Calculate the Sum of Digits of a Given Number
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}")
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:
digit_sumThe function accepts an integernumberas a parameter.str(number)Convert the integer to a string so that it can be iterated character by character.int(digit) for digit in str(number)is a generator expression that converts each character in the string back to an integer.sum(...)The function adds these integers to obtain the sum of the digits.- Finally, we use the
printfunction to output the result.
Output result:
The sum of digits of 12345 is 15Other extensions
Python3 Examples