Sum of Digits Calculator

  • Share this:

Code introduction


Calculates the sum of all digits of an integer.


Technology Stack : Built-in type checking (isinstance), exception handling (raise), arithmetic operations (% and //), looping (while)

Code Type : Function

Code Difficulty :


                
                    
def sum_digits(n):
    if not isinstance(n, int):
        raise ValueError("Input must be an integer.")
    
    total = 0
    while n > 0:
        total += n % 10
        n //= 10
    return total