Notification texts go here Contact Us Buy Now!

Calculating Sum of Digits in a Number Using Python

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.

About the Author

Coding | Riding | Music, Embracing the beauty of code, the thrill of the ride, and the rhythm of life. Let's explore the journey together!

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.
Code Copied!