Read a whole number and print the sum of its digits. Use a while loop with % 10 and // 10.
What to build
A loop that takes a number apart.
Requirements
- Read the number.
- Add up its digits using
% 10and// 10in awhileloop.
Input
One whole number from 0 to 1000000000.
Output
The sum of its digits.
Constraints
The number is from 0 to 1000000000.
Example
Input:
4728
Output:
21
Why it works
% 10 gives the last digit and // 10 removes it, so each pass leaves a smaller number until nothing is left.
Examples
Example 1 · Input
4728
Expected output
21
Example 2 · Input
0
Expected output
0
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
n % 10 is the last digit; n // 10 removes it.
Solution
Show one correct solution (try it yourself first)
n = int(input())
total = 0
while n > 0:
total += n % 10
n //= 10
print(total)