Sum of Digits
Easypython
Read a whole number and print the sum of its digits, using a while loop.
Approach: repeatedly take the last digit with n % 10, add it to a running total, then remove that digit with n //= 10, until n becomes 0.
Input: One line: a whole number n (may be negative — use its digits regardless of sign).
Output: One line: Sum of digits: <total>
Example 1
Input
1234
Output
Sum of digits: 10
- -10^9 <= n <= 10^9
Hint 1
n % 10 gives the last digit; n //= 10 removes it.
Hint 2
Loop while n > 0, adding each digit to a running total.
Hint 3
Take the absolute value first so negative numbers work the same way.
Take the absolute value so the sign doesn't matter, then repeatedly peel off the last digit with n % 10, add it to a running total, and shrink n with integer division n //= 10 until nothing is left.