Python-多用户输入

时间:2014-01-30 18:16:31

标签: loops python-2.7 calculator infinite

我试图在python上多次获取用户输入,然后取其总和。

多次进行用户输入意味着我每次都需要一个新变量来存储用户输入。我需要一个可以接受无限用户输入的程序,并且当然不可能将新变量分配给无限用户输入并添加它们。 python中是否有内置函数可以继续添加值?

这是我的代码。因为哨兵而没有给我这笔钱(我不明白为什么)。 请帮忙。

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

1 个答案:

答案 0 :(得分:0)

试试这个:

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

这将接受任何输入并将其转换为浮点数,将其添加到总数中,如果输入为0,则返回总数。

为了使这更灵活,您可以使用以下更改来添加所有数字(包括0)并在用户输入任何内容时退出。

total = float(raw_input('enter a number: '))
while True:
    number = raw_input('enter a number: ')
    if number == '':
        break
    total+=float(number)