Question

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 ()

Was it helpful?

Solution

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top