2013-10-17 60 views
1

剛剛開始使用較舊的Python書籍,瞭解循環並嘗試創建一個累積用戶輸入的循環,然後顯示總計。問題是這本書只顯示瞭如何使用範圍做到這一點,我想讓用戶輸入任意數量的數字,然後顯示總數,例如,如果用戶輸入了1,2,3,4,我會需要python輸出10,但我不想讓python綁定到一系列數字。 這裏是我有一個範圍的代碼,正如我上面所述,我需要做這個用戶輸入,而不是被束縛在一個範圍內。我是否也需要爲我想要製作的節目申請一個哨兵?Python 2.7.5,無限用戶輸入循環,積累總數,應用哨兵?

def main(): 

    total = 0.0 

    print ' this is the accumulator test run ' 
    for counter in range(5): #I want the user to be able to enter as many numbers 
     number = input('enter a number: ') #as they want. 
     total = total + number 
    print ' the total is', total 

main() 
+0

你嘗試過'而TRUE'? – Brian

+0

您正在尋找一個while循環:http://docs.python.org/2/reference/compound_stmts.html#while。 – Jblasco

回答

0

這裏您需要while-loop

def main(): 
    total = 0.0 
    print ' this is the accumulator test run ' 
    # Loop continuously. 
    while True: 
     # Get the input using raw_input because you are on Python 2.7. 
     number = raw_input('enter a number: ') 
     # If the user typed in "done"... 
     if number == 'done': 
      # ...break the loop. 
      break 
     # Else, try to add the number to the total. 
     try: 
      # This is the same as total = total + float(number) 
      total += float(number) 
     # But if it can't (meaning input was not valid)... 
     except ValueError: 
      # ...continue the loop. 
      # You can actually do anything in here. I just chose to continue. 
      continue 
    print ' the total is', total 
main() 
+0

什麼是+ =運算符?爲什麼在嘗試之後使用它? – JuanB457

+0

@ JuanB457 - 它與'total = total + float(number)'相同。這只是一個更清晰的寫作方式。 – iCodez

0

使用相同的邏輯,只用while循環代替它。退出循環,當用戶鍵入0

def main(): 
    total = 0 
    print 'this is the accumulator test run ' 
    while True: 
     number = input('enter a number: ') 
     if number == 0: 
      break 
     total += number 
    print 'the total is', total 

main() 

只是爲了好玩,這裏是一個在線解決方案:

total = sum(iter(lambda: input('Enter number (or 0 to finish): '), 0)) 

如果你想讓它馬上顯示:

print sum(iter(lambda: input('Enter number (or 0 to finish): '), 0)) 
+0

@iCodez呃,它實際上*確實*工作,所以請在您提出指控之前檢查。 –

+0

@iCodez:'input()'在Python 2中工作。它將輸入解釋爲任意Python代碼(不安全!)。 –

0

使用while循環循環的次數不定數:

total = 0.0 
print 'this is the accumulator test run ' 
while True: 
    try: 
     # get a string, attempt to cast to float, and add to total 
     total += float(raw_input('enter a number: ')) 
    except ValueError: 
     # raw_input() could not be converted to float, so break out of loop 
     break 
print 'the total is', total 

測試運行:

this is the accumulator test run 
enter a number: 12 
enter a number: 18.5 
enter a number: 3.3333333333333 
enter a number: 
the total is 33.8333333333