2013-03-05 49 views
6

我在Python 3.3中有一個try-except塊,我希望它無限期地運行。如何重複try-except塊

try: 
    imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low")) 
except ValueError: 
    imp = int(input("Please enter a number between 1 and 3:\n> ") 

目前,如果用戶輸入一個非整數,將工作按計劃進行,但如果他們要重新進入,它只是再次提高ValueError異常和崩潰。

解決此問題的最佳方法是什麼?

回答

12

把它放在一個while循環中,當你得到你期望的輸入時就發生。如下所示,最好將imp中的所有代碼都保存在try中,或者設置其默認值以防止NameError進一步下降。

while True: 
    try: 
    imp = int(input("Importance:\n\t1: High\n\t2: Normal\n\t3: Low")) 

    # ... Do stuff dependant on "imp" 

    break # Only triggered if input is valid... 
    except ValueError: 
    print("Error: Invalid number") 
6
prompt = "Importance:\n\t1: High\n\t2: Normal\n\t3: Low\n> " 
while True: 
    try: 
     imp = int(input(prompt)) 
     if imp < 1 or imp > 3: 
      raise ValueError 
     break 
    except ValueError: 
     prompt = "Please enter a number between 1 and 3:\n> " 

輸出:

[email protected]:~$ python3 test.py 
Importance: 
    1: High 
    2: Normal 
    3: Low 
> 67 
Please enter a number between 1 and 3: 
> test 
Please enter a number between 1 and 3: 
> 1 
[email protected]:~$