Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Addition of integer input through while loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading