Start free

Beginner · While loops · 84 of 264

Add until zero

Keep reading numbers and adding them up until you read 0. Print the total.

Input: whole numbers, one per line; the last one is 0. Output: the sum of the numbers before the 0.

Examples

Input
5
3
2
0
Output
10
Input
0
Output
0
Input
-1
-2
10
0
Output
7

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.

All the while loops exercises
Your code
Opening the code editor…
Python 3.14 in your browser
Output
Run shows what your program prints. Check tests it on every example and the hidden tests.

More while loops exercises