Sum of Digits in Python
Compute the sum of digits of an integer using a loop.
BeginnerLoop ProgramsExample 4 of 25
sum-of-digits.py
Run in browser1# Program to find the sum of digits of a number23num = int(input("Enter an integer: "))45total = 06temp = abs(num)78while temp > 0:9 digit = temp % 1010 total += digit11 temp //= 101213print("Sum of digits of", num, "is", total)
Output
Enter an integer: 1234 Sum of digits of 1234 is 10
What's going on
We repeatedly extract the last digit with % 10, add it to a running total, and remove it using integer division // 10.