2014-10-20 71 views
0

我有這樣的功能:停止循環和返回值,如果它不給錯誤

def int_input(promt): 
    while True: 
      try: 
        int(promt) 
      except ValueError: 
        print "Not a number, try again." 
        promt = raw_input("Enter your choice:") 

我希望它在某些時候打破返回PROMT,如果它是一個數字,我似乎無法找到合理的方法。

+1

'返回INT(提示)'? – GP89 2014-10-20 16:30:46

回答

4

不是100%確定你在做什麼,但是如果你調用它,它將不會返回,直到你輸入一個有效的int。

def int_input(): 
    while True: 
     try: 
      return int(raw_input("Enter your choice:")) 
     except ValueError: 
      print "Not a number, try again." 

print int_input() 

輸出

Enter your choice: asdf 
Not a number, try again. 
Enter your choice: 2df 
Not a number, try again. 
Enter your choice: 3 
3 
+0

必須使用promt調用函數,但這很容易修復,謝謝。 :) – 2014-10-20 16:45:41

0

這是否你想要做什麼:

def int_input(promt): 
    while True: 
     try: 
      int(promt) 
     except ValueError: 
      print "Not a number, try again." 
      promt = raw_input("Enter your choice:") 
      continue 

     return int(promt) 
+0

確實如此,謝謝。 但是,如果這是我首先輸入的內容,它會返回一個字母 – 2014-10-20 16:37:45

0

try .. except有一個可選的else條款:

def int_input(promt): 
    while True: 
      try: 
        int(promt) 
      except ValueError: 
        print "Not a number, try again." 
        promt = raw_input("Enter your choice:") 
      else: # no exception occured, we are safe to leave this loop 
       break # or return, or whatever you want to do... 

但這時並不需要在這裏,你可以簡單地裏面的returnbreaktry(僅在int()期間沒有異常時纔會達到int()強制轉換。

0

Ngenator的回答是有點清潔,但你可以設置一個變量作爲開關,表示你有一個正確的值:

 
def int_input(promt): 
    got_int = False 
    while not got_int: 
      try: 
        int(promt) 
        got_int = True 
      except ValueError: 
        print "Not a number, try again." 
        promt = raw_input("Enter your choice:")