Write a Python function to calculate the sum of digits of a number.
Posted by MaryJns
Last Updated: August 17, 2024
Python Function to Calculate the Sum of Digits
Calculating the sum of the digits of a number can be efficiently accomplished by converting the number to a string, iterating through each character, converting each back to an integer, and summing them up. Below is a Python function that demonstrates this approach.
def sum_of_digits(number):
    """
    Calculate the sum of the digits of a given integer.

    Parameters:
    number (int): The integer whose digits are to be summed.

    Returns:
    int: The sum of the digits of the number.
    """
    # Ensure the number is non-negative
    number = abs(number)
    
    # Convert the number to string and iterate over each digit
    digit_sum = sum(int(digit) for digit in str(number))
    
    return digit_sum

# Example usage
if name == "main":
    num = 12345
    result = sum_of_digits(num)
    print(f"The sum of digits in {num} is {result}.")
Explanation of the Code
1. Function Definition: The function sum_of_digits takes one argument, number, which is the integer whose digits you want to sum. 2. Handle Negative Numbers: The abs() function is used to convert negative numbers to their positive counterparts, ensuring the sum of digits is always calculated correctly regardless of the sign. 3. Digit Extraction and Summation: The number is first converted to a string to allow iteration over each digit. A generator expression is used within the sum() function to convert each character back to an integer and compute the cumulative sum. 4. Return Statement: The function returns the total sum of the digits. 5. Example Usage: An example is provided illustrating how to call the function and display the result. This function is efficient and works for any integer input. It is also easy to understand, making it a great addition to any Python programming toolkit.