How to receive a num at each step and continue until zero is entered; then this program should print the sum of enter nums

Question:

How to Write a program that receive a number from the input at each step and continue to work until zero is entered. After the zero digit is entered, this program should print the sum of the entered numbers. I want to get n different numbers in n different lines and it stops when it reaches Zero

For ex:(input:)

3

4

5

0

Output:

12

Actually I have this code but it doesn’t work:
‘’’python’’’

Sum= 0

Num = int(input())

While num!=0 :

   Num = int(input())

   Sum+= num

Print(sum)

But it gives ‘9’ instead of ‘12’

Asked By: Qazaaleh Taheri

||

Answers:

Here I’m using a while loop that continues until the user input is 0 then prints out the sum.

res = 0
user_input = int(input('Input a number: '))
while user_input != 0:
    res+= user_input
    user_input=int(input('Input a number: '))

print("You entered 0 so the program stopped. The sum of your inputs is: {}".format(res))
Answered By: kimo26

Code:-

total_sum=0
n=int(input("Enter the number: "))
while n!=0:
    total_sum+=n
    n=int(input("Enter the number: "))
print("The total sum until the user input 0 is: "+str(total_sum))

Output:-

#Testcase1 user_input:- 10, 0

Enter the number: 10
Enter the number: 0
The total sum until the user input 0 is: 10

#Testcase2 user_input:- 3, 4, 5, 0

Enter the number: 3
Enter the number: 4
Enter the number: 5
Enter the number: 0
The total sum until the user input 0 is: 12

#Improvisation – { Removing the redundancy of n initialization in above code (which is two times before the while loop and inside the while loop)}

Code:-

total_sum=0
while True:
    n=int(input("Enter the number: "))
    total_sum+=n
    if not n:
        break
print("The total sum until the user input 0 is: "+str(total_sum))

Output:-

Same as above

Answered By: Yash Mehta
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.