Python while loops and digit processing
Repeat until a changing condition becomes false.
Python
def digit_sum(number):
number = abs(number)
total = 0
while number > 0:
total += number % 10
number //= 10
return total
print(digit_sum(204))
assert digit_sum(0) == 0
assert digit_sum(-204) == 6Output
6
Explanation
A while loop checks its condition before every iteration, so its body may run zero times. A termination argument explains why the loop eventually stops.
For a nonnegative integer, n % 10 extracts the last decimal digit and n // 10 removes it. The function uses abs so negative inputs have the same digit sum as their magnitudes.
Explore the dry run
Guided walkthroughReady
1
def digit_sum(number):2
number = abs(number)3
total = 04
while number > 0:5
total += number % 106
number //= 107
return total8
9
print(digit_sum(204))10
assert digit_sum(0) == 011
assert digit_sum(-204) == 6Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Start with 204. | number = 204 | — | |
| Initialize the sum. | total = 0 | — | |
| Extract the last digit 4. | number = 204, total = 4 | — | |
| Remove that digit. | number = 20 | — | |
| Add the next digit, 0. | total = 4 | — | |
| Remove the zero. | number = 2 | — | |
| Add the final digit 2. | total = 6 | — | |
| Reach zero, so the next condition is false. | number = 0 | — | |
| Return and print 6. | number = 0 | 6 | |
| Check zero and negative inputs without extra output. | number = 0 | 6 |
Cost and common mistakes
O(d) iterations and O(1) stored variables for d decimal digits; arbitrary-precision arithmetic costs grow with integer size.
- Omitting number //= 10 would prevent termination for positive inputs.
- This example accepts integers, not decimal strings or floating-point values.
Try it yourself
Trace digit_sum(1002).
Reveal answer and reasoning
The extracted digits are 2, 0, 0, 1 and the result is 3.