Python Module Importing: The Good, Bad, and Ugly

Use a for loop to iterate through each digit in the number, convert it to an int using the ord() function (since all ASCII digits have their codes between 48 and 57), and add them up. Finally, return the sum of digits as an integer. Make sure your code is well-documented with clear comments explaining each step.

Here’s a possible implementation:

# Define a function to calculate the sum of all digits in a given number
def sum_of_digits(num):
    """Calculate the sum of all digits in a given number."""
    total = 0 # Initialize variable to store the running total
    
    # Check for negative numbers
    if num < 0:
        num *= -1 # Convert negative input to positive (for easier processing)
        
    # Loop through each digit of the number
    while True:
        # Get last digit using slicing and convert it to an int using the ord() function
        digit = ord(str(num)[-1])
        total += digit # Add current digit to running total
        num //= 10 # Remove last digit from input (for next iteration)
        
        # Check for single-digit number
        if len(str(num)) == 1:
            break # Exit loop when only one digit left
    
    return total # Return the sum of digits as an integer

Explanation:
The function `sum_of_digits()` takes an integer as input and returns its sum of digits. The first step is to initialize a variable called `total`, which will store the running total for all digit sums.

Next, we check if the number is negative using an if statement. If it’s negative, we convert it to positive by multiplying it with -1 (for easier processing). This is because converting digits to their ASCII codes requires us to treat them as strings, and since `ord()` returns the code for the first character of a string, we need to make sure that all characters are treated equally.

We then use a while loop to iterate through each digit in the number. We get the last digit using slicing (i.e., `str(num)[-1]`) and convert it to an int using the `ord()` function. This is because we need to treat digits as strings so that we can use string indexing, but we also want to add them up as integers.

We then add the current digit to our running total (i.e., `total += digit`) and remove it from the input by dividing the number with 10 using integer division (i.e., `num //= 10`). This is because we want to iterate through each digit in reverse order, starting from the rightmost one.

Finally, we check if there’s only one digit left (i.e., `len(str(num)) == 1`) and exit the loop when that happens. We then return the sum of digits using the `return` statement.

SICORPS