Home > Enterprise >  How to sum input numbers using while loop? (python)
How to sum input numbers using while loop? (python)

Time:04-11

Beginner question, I have to create a program that asks user to input numbers (input 0 to break), then calculates the amount of numbers in total and then the sum of the input numbers. How do i print the sum of user-input numbers using while loop? This is what I got so far

amount = 0
while True:
    amount  = 1
    number = int(input("Number: "))
    if number == 0:
        break
    
print(f"Numbers in total: {amount-1}")

CodePudding user response:

You are close. Same as you have amount = 0, create a variable total = 0. And, inside the loop, add total = number, after the line where you are reading it.

CodePudding user response:

You can simply use the same technique that you used for the number of inputs:

amount = 0
number = 0
while True:
    amount  = 1
    number  = int(input("Number: "))
    if number == 0:
        break

print(f"Numbers in total: {amount-1}")
print(f"Sum of the numbers : {number}")

CodePudding user response:

number_of_numbers=0
total_sum=0
while True:
    number = int(input("Number: "))
    if number == 0:
        break
    number_of_numbers  = 1
    total_sum  = number

print("Total number of numbers is: ", number_of_numbers)
print("Total sum is: ", total_sum)

You were almost there, just had to add another variable for obtaining the total sum. Apart from that, it's almost the same as your code. Just that added the if condition before adding the total number.

CodePudding user response:

Something like this should work:

iteration = 0
amount = 0
while True:
    iteration  
    number = int(input("Number: "))
    if number == 0:
        break
    amount  = number
    print(f"Sum so far: {amount}")
    
print(f"Numbers in total: {iteration-1}")
  • Related