The sum of the digits of 9875 is 9 + 8 + 7 + 5 = 29. This page shows the arithmetic way (with % and //) and the string way.
The program
python
n = int(input("Enter a number: ")) number = abs(n) total = 0 while number > 0: total += number % 10 number //= 10 print(f"Sum of digits of {n} = {total}")
Typed in this example: 9875. Press Run to type your own.
output
Enter a number: 9875 Sum of digits of 9875 = 29
How it works
number % 10gives the last digit: 9875 % 10 is 5.number //= 10removes the last digit: 9875 // 10 is 987.- The loop repeats until no digits are left (
numberbecomes 0). The digits are added in the order 5, 7, 8, 9. abs(n)removes the minus sign, so -9875 also gives 29. Without it, the loop would not run for a negative number, becausenumber > 0would be false.- For 0, the loop does not run and the sum is 0, which is correct.
Another way: with a string
str(n) turns the number into text, and a loop over a string gives one character at a time:
python
n = -9875 total = sum(int(digit) for digit in str(abs(n))) print(total)
output
29
int(digit) turns each character, such as "9", back into a number before it is added. The string way is shorter. The arithmetic way is worth knowing, because the same % 10 and // 10 steps are used to reverse a number and to count digits.