0

I'm trying to create a while loops where you can input as many integers as you want. The input gets summed up and printed only when I type in the number 0.

Currently I have written the following:

n = int(input())
sum = 0 

while n != 0:
  sum = sum + n 
print(sum)

When I enter in the 0 value the loop does not close and my sum is not printed.

Is there something I'm missing?

Thank you in advance!

I'm expecting the loop to close when I type in 0 which should give the sum of all the number entered previously.

e.g.

Input:
2
3
1
0


Output:

6
1
  • You never change n so n != 0 is indefinitely True (unless input is 0) Commented Nov 11, 2022 at 13:14

1 Answer 1

1

The Problem here is that you can only input 1 number than the code is stuck in the while loop. So if you want to sum multiple inputs the input needs to be in the while loop. Try this..

result = 0
while True:
    n = int(input())
    if n == 0:
        print(result)
        break
    else:
        result += n
Sign up to request clarification or add additional context in comments.

1 Comment

Better not to shadow built-in names. (sum)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.