2017-07-19 36 views
3

我想檢查我的輸入是否是數字,並在同一時間範圍(1,3),並重復輸入,直到我得到滿意的答案。 現在我這樣做,但代碼很不乾淨,容易...有沒有更好的方法來做到這一點? 也許與while循環?如何檢查輸入是否同時位於數字和範圍內? Python

def get_main_menu_choice(): 
    ask = True 
    while ask: 
     try: 
      number = int(input('Chose an option from menu: ')) 
      while number not in range(1, 3): 
       number = int(input('Please pick a number from the list: ')) 
      ask = False 
     except: # just catch the exceptions you know! 
      print('Enter a number from the list') 
    return number 

將不勝感激。

回答

1

我想這樣做的最乾淨的方法是刪除雙循環。但是,如果你想循環和錯誤處理,無論如何你都會得到一些令人費解的代碼。我會親自去爲:

def get_main_menu_choice(): 
    while True:  
     try: 
      number = int(input('Chose an option from menu: ')) 
      if 0 < number < 3: 
       return number 
     except (ValueError, TypeError): 
      pass 
0

如果整數數爲1和2之間(或者它是否在範圍內(1,3)),它已經意味着它是一個數字

while not (number in range(1, 3)): 

我將簡化爲:

while number < 1 or number > 2: 

while not 0 < number < 3: 

你的代碼的簡化版本有嘗試,唯獨身邊的唯一int(input())

def get_main_menu_choice(): 
    number = 0 
    while number not in range(1, 3): 
     try: 
      number = int(input('Please pick a number from the list: ')) 
     except: # just catch the exceptions you know! 
      continue # or print a message such as print("Bad choice. Try again...") 
    return number 
+0

但我需要保護當有人輸入空字符串(回車)或字母。我需要問他們的輸入,直到他們輸入數字1或2. – JeyKey

+0

啊,我誤解了你的問題。看來你對處理'except'感興趣! –

+0

@JeyKey我已經添加了你的代碼的簡化版本。 –

0

看看這個工作小號

def get_main_menu_choice(): 
    while True: 
     try: 
      number = int(input("choose an option from the menu: ")) 
      if number not in range(1,3): 
       number = int(input("please pick a number from list: ")) 
     except IndexError: 
      number = int(input("Enter a number from the list")) 
    return number 
0

如果您需要做對非數字的驗證,以及你將不得不添加幾個步驟:通過傳遞列表

def get_main_menu_choice(choices): 
    while True: 
     try: 
      number = int(input('Chose an option from menu: ')) 
      if number in choices: 
       return number 
      else: 
       raise ValueError 
     except (TypeError, ValueError): 
      print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1])) 

然後你就可以重新使用它的任何菜單有效的選擇,例如get_main_menu_choice([1, 2])get_main_menu_choice(list(range(1, 3)))

0

我會寫這樣的:

相關問題