我想檢查我的輸入是否是數字,並在同一時間範圍(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或2. – JeyKey
啊,我誤解了你的問題。看來你對處理'except'感興趣! –
@JeyKey我已經添加了你的代碼的簡化版本。 –