Python while loops and digit processing

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.

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) == 6
Read the full lesson