2011-05-11 101 views
2

我試圖支持重複在用戶輸入文件名,然後輸入兩個整數。所以如果拋出異常,我希望用戶再次被提示輸入。蟒蛇嘗試/例外幫助

我的問題是,如果輸入了一個有效的文件,但輸入了一個無效的整數,它將再次要求文件而不是整數。我該如何修復代碼,以便再次詢問整數。

以下是我有:

while True: 
    try: 
     f = raw_input("Enter name of file: ") 
     inFile = open(f) 
     # more code 
    except IOError: 
     print ("The file does not exist. Try Again.")   
    else:  
     try: 
      integer = int(raw_input("Enter an integer: ")) 
      integer2 = int(raw_input("Enter an integer: ")) 
      # more code 
     except (TypeError, ValueError): 
      print ("Not an integer. Try Again.") 

回答

9

嘗試使用多個while循環:

while True: 
    fileName = raw_input("Enter name of file: ") 
    try: 
     # more code here to detect or open the file 
     break 
    except Exception: # can be IOError or something else 
     print ("error msg") 

while True: 
    try: 
     integer = int(raw_input("Enter an integer: ")) 
     integer2 = int(raw_input("Enter an integer: ")) 
     break 
    except (TypeError, ValueError): 
     print ("error msg") 

# more code 
+0

該死您34秒:( – 2011-05-11 09:20:08

+0

感謝,多重循環的工作!但是,當在第二循環中說,進入第一個整​​數是有效的,但第二個整數進入打我的標誌是無效的,它會提示你重新輸入這兩個整數,是否可以只提示最後一個整數N + – michael 2011-05-11 09:31:02

+0

@michael,你可以將第二個循環分成兩個循環,每個循環爲'raw_input' – 2011-05-11 09:37:16

0
while True: 
    try: 
     a = int(raw_input('a: ')) 
     b = int(raw_input('b: ')) 
     break 
    except ValueError: 
     print "Numbers idiot" 
#more code here 

此代碼將跳轉到不同的塊a或b,並與更多的進行如果數字有效,請輸入代碼

0
>>> def ask(question, func, exceptions): 
...  while True: 
...   try: 
...    return func(raw_input(question)) 
...   except exceptions, error: 
...    pass 
... 
>>> x = ask("integer?", int, ValueError) 
integer?o 
integer?l 
integer?42 
>>> x 
42 
0

,就答案擴大上述使用多個while循環和關於處理額外的數據驗證,而不必遍歷已經覈實數據的相關問題,下面看起來這些混沌有關,但它給你的顆粒狀檢查你尋找實現:

while True: 
    fileName = raw_input("Enter name of file: ") 
    try: 
     # more code here to detect or open the file 
     break 
    except Exception: 
     print ("The file does not exist. Try Again.") 

while True: 
    try: 
     integer = int(raw_input("Enter an integer: ")) 
     break 
    except (TypeError, ValueError): 
     print ("Not an integer. Try Again.") 

while True: 
    try: 
     integer2 = int(raw_input("Enter an integer: ")) 
     break 
    except(TypeError, ValueError): 
     print ("Not an integer. Try Again.")