Write a function that sums the digits of a non-negative integer.
digit_sum(n)
Do it with a while loop and arithmetic (% and //) — don't convert n to a string.
digit_sum(1234) // → 10 (1+2+3+4)
digit_sum(9) // → 9
digit_sum(100) // → 1
digit_sum(55555) // → 25
This is exactly the kind of problem where you don't know the number of iterations ahead of time — a number could have 1 digit or 10 — which is the signature of a while loop from the lesson.
def digit_sum(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total
Two arithmetic tricks do all the work:
n % 10 is the remainder when dividing by 10 — for any integer, that's exactly its last digit. 1234 % 10 is 4.n // 10 is floor division by 10 — it removes the last digit. 1234 // 10 is 123.Each loop iteration peels off one digit (adding it to total) and shortens n by one digit, until n reaches 0 and the loop condition n > 0 becomes false — that's the "something moves toward making the condition false" requirement from the for-vs-while lesson, and it's what guarantees this loop actually terminates.
Trace 1234: total=0, n=1234 → add 4, n=123 → add 3, n=12 → add 2, n=1 → add 1, n=0, loop stops. total = 4+3+2+1 = 10. ✓
def digit_sum(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.