Beginner · While loops · 82 of 264
Sum of the digits
Add up the digits of a whole number of any length using a while loop.
Input: a positive whole number. Output: the sum of its digits.
Examples
Input
12345
Output
15
Input
9
Output
9
Input
1000001
Output
2
One more test checks other inputs when you press Check.
Stuck? The idea behind while loops
A while loop repeats as long as its condition is true: use it when you don't know in advance how many times.
Something inside the loop must change, so the condition becomes false in the end.
n = int(input())
digits = 0
while n > 0:
n //= 10
digits += 1
print(digits)Watch for: If nothing in the loop changes the condition, it never ends and the program is stopped after a few seconds.