I am trying to take user input multiple times on python and then taking its sum.

Taking user input multiple times means i need a new variable each time to store the user input.I need a program which can take infinite user inputs and ofcourse its impossible to assign a new variable to infinite user inputs and add them up. Is there any built-in function in python which can keep on adding the values itself?

Here is my code.It doesnt give me the sum because of sentinel(I dont understand why). Please help.

var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division      respectively: "))
if var == 1:
 print "You chose to add.Lets add!! :)"
def main ():
 total = 0.0
 while True:
  number = int(raw_input('enter a number: '))
  if number == 0:
  total+=number
  break
  print 'the total is', total

main ()

有帮助吗?

解决方案

Try this:

var = int(raw_input("Enter 1,2,3 or 4 for add,subtract,multiplication,division      respectively: "))
if var == 1:
    print "You chose to add.Lets add!! :)"

def main ():
    total = 0.0
    while True:
        number = float(raw_input('enter a number: '))
        total+=number
        if number == 0:
            break
    print 'the total is', total

main()

This will take any input and covert it to a float, add that to your total and, if the input is 0 then return your total.

To make this more flexible you can use the following change that will add all numbers (including 0) and exit when nothing is entered by the user.

total = float(raw_input('enter a number: '))
while True:
    number = raw_input('enter a number: ')
    if number == '':
        break
    total+=float(number)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top