Sum of Digits

Compute the sum of digits of an integer using a loop.

PythonBeginner
Python
# Program to find the sum of digits of a number

num = int(input("Enter an integer: "))

total = 0
temp = abs(num)

while temp > 0:
    digit = temp % 10
    total += digit
    temp //= 10

print("Sum of digits of", num, "is", total)

Output

Enter an integer: 1234
Sum of digits of 1234 is 10

We repeatedly extract the last digit with % 10, add it to a running total, and remove it using integer division // 10.