2014-01-30 65 views
0

我想在python上多次輸入用戶輸入,然後取其總和。Python-多用戶輸入

多次輸入用戶輸入意味着每次都需要一個新變量來存儲用戶輸入。我需要一個可以接受無限用戶輸入的程序,並且當然不可能爲無限用戶輸入指定一個新變量並將其添加。 Python中是否有任何內置函數可以繼續添加值本身?

這是我的code.It不給我總和,因爲哨兵(我不明白爲什麼)。 請幫忙。

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

回答

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) 
+0

**,如果我想爲乘法做同樣的什麼?** 我看了有在巨蟒數量的產品沒有內置功能好像有加法,即SUM(數量)。我不能使用列表作爲用戶輸入在這裏不斷變化。 – susan

+0

@susan如果你想爲乘法做同樣的事情,你可以將'total + = number'改爲'total * = number' – Ewan

+0

試過了。但是我應該怎麼改變最後一行呢?即 **打印「總數」,共** 不給乘積。 並且相同的循環不適用於減法,總計= 它只是「增加」了「負值」值。 – susan