2015-11-17 58 views
0

我當前的代碼可以工作,但是當出現選項菜單時,我選擇了一個選項,它應該再次從選擇中重複,但是我的代碼從開始時重新開始,它要求輸入數字而不是輸入一個選項。Python在while循環中正確定位

n = 0 
amount = 0 
total = 0 

while n != "": 
    try: 
     n=int(input("Enter a number: ")) 
     amount = amount+1 
     total = total + n 
    except ValueError: 
     average = total/amount 


     print() 
     print("Which option would you like?") 
     print("1 - Number of values entered") 
     print("2 - Total of the values entered") 
     print("3 - Average of values entered") 
     print("0 - Exit") 

     choice = int(input("Enter your choice: ")) 
     if choice == 1: 
      print(amount, "numbers were input.") 


     elif choice == 2: 
      print("The total of the sequence is", total) 

     elif choice == 3: 
      print("The average is",average) 

     elif choice == 0: 
      print("Exit") 
      break 

因此,這意味着我需要while循環中重新調整我的代碼,或採取輸入級到不同的位置?

+0

'N = 「」'不看我的權利! 'n'總是一個整數。沒有整數將永遠等於空字符串。 – Kevin

+0

我用「ValueError」部分解決了這個問題。我的代碼運行和所有,它只是從錯誤的部分重複 – Xrin

回答

1

你需要一個嵌套循環

(試圖改變你原來的代碼儘可能少),我改變了它包括一個while循環(除while循環之外的另一個break語句中的選項菜單,以確保程序不會重複(除非你想要...))。

n = 0 
amount = 0 
total = 0 

while n != "": 
    try: 
     n=int(input("Enter a number: ")) 
     amount = amount+1 
     total = total + n 
    except ValueError: 
     average = total/amount 

     choice = -1   # new 
     while(choice != 0): # new 
      print() 
      print("Which option would you like?") 
      print("1 - Number of values entered") 
      print("2 - Total of the values entered") 
      print("3 - Average of values entered") 
      print("0 - Exit") 

      choice = int(input("Enter your choice: ")) 
      if choice == 1: 
       print(amount, "numbers were input.") 


      elif choice == 2: 
       print("The total of the sequence is", total) 

      elif choice == 3: 
       print("The average is",average) 

      elif choice == 0: 
       print("Exit") 
       break 
     break # new 

記住這可能是一個很好的協議更穩健,且存在處理中指定的外選擇的選項沒有的功能(不過應該有人進入5或東西則只會重複)

+0

哦,我明白了,謝謝;我跑過去了,這很有道理。它驚人的簡單的事情可以是,但我覺得是經驗的關鍵。另外我注意到你在休息結束時放了一個半結腸,我刪除了那個,因爲我相信這是用在java – Xrin

+0

哦,上帝,你是對的;我經常在C++和Python之間切換,所以我似乎無法放棄那種骯髒的習慣。固定 – AudreyM

0

有時候我會發現自己永遠擁有自己的應對循環,並且在必要時可以打破它。我也嘗試在可能的情況下減少嵌套,並且我不喜歡將異常處理用於有效的輸入選項。這裏有一個稍微返工例如:

量= 0 總= 0

while True: 
    n = input("Enter a number: ") 
    if n == "": 
     break 
    amount = amount+1 
    total = total + int(n) 

average = total/amount 

while True:  
    print() 
    print("Which option would you like?") 
    print("1 - Number of values entered") 
    print("2 - Total of the values entered") 
    print("3 - Average of values entered") 
    print("0 - Exit") 

    choice = int(input("Enter your choice: ")) 
    if choice == 1: 
     print(amount, "numbers were input.") 

    elif choice == 2: 
     print("The total of the sequence is", total) 

    elif choice == 3: 
     print("The average is",average) 

    elif choice == 0: 
     print("Exit") 
     break