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
CodePudding user response:
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