Hey there, bloggers!
In this post, we'll explore a simple Python function to calculate the sum of all digits in a given number.
The Python Function
Here's the Python function:
def sum_of_digits(number):
# Convert the number to a string to iterate through its digits
num_str = str(number)
# Initialize sum to store the total sum of digits
total_sum = 0
# Iterate through each digit in the string
for digit in num_str:
# Convert the digit back to an integer and add it to the total sum
total_sum += int(digit)
# Return the total sum
return total_sum
# Example usage:
number = 12345
print("Sum of digits in", number, "is:", sum_of_digits(number))
Explanation
This function takes a number as input, converts it to a string, iterates through each digit in the string, converts it back to an integer, and adds it to the total sum. Finally, it returns the total sum of digits.
Example Usage
Let's say we have the number 12345. Using the function, the sum of digits in this number would be calculated as follows:
sum_of_digits(12345)
# Output: 15
So, the sum of digits in 12345 is 15.
That's it! You now have a handy Python function to calculate the sum of digits in any given number.