Python while loops and digit processing
Repeat until a changing condition becomes false.
On this page
Integer division, remainder, and conditions.
- Repeat until a changing condition becomes false.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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) == 66
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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) == 0assert 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 |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
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.