2014-04-27 163 views
0

我正在嘗試進行一項允許用戶從選項1-x中選擇的多項選擇調查。我怎樣才能讓這個如果用戶輸入任何字符,除了數字,返回類似「這是一個無效的答覆」除其他我如何限制用戶輸入爲Python中的整數

def Survey(): 
    print('1) Blue') 
    print('2) Red') 
    print('3) Yellow') 
    question = int(input('Out of these options\(1,2,3), which is your favourite?')) 
    if question == 1: 
     print('Nice!') 
    elif question == 2: 
     print('Cool') 
    elif question == 3: 
     print('Awesome!') 
    else: 
     print('That\'s not an option!') 
+0

捕獲異常 –

回答

4

您的代碼將變爲:

def Survey(): 

    print('1) Blue') 
    print('2) Red') 
    print('3) Yellow') 

    while True: 
     try: 
      question = int(input('Out of these options\(1,2,3), which is your favourite?')) 
      break 
     except: 
      print("That's not a valid option!") 

    if question == 1: 
     print('Nice!') 
    elif question == 2: 
     print('Cool') 
    elif question == 3: 
     print('Awesome!') 
    else: 
     print('That\'s not an option!') 

這種方式的工作原理是它會形成一個循環,無限循環,直到只有數字被放入。所以說我把'1',它會打破循環。但是如果我把'Fooey!' 012UL聲明捕捉到WOULD提出的錯誤,並且它沒有被破壞而循環。

+0

非常感謝,這是正是我需要的! – user3578683

+0

沒問題,很高興我能幫到你。 – HarryCBurn

1

一個解決方案:使用type功能或isinstance功能檢查,如果你有一個intfloat或一些其他類型的

>>> type(1) 
<type 'int'> 

>>> type(1.5) 
<type 'float'> 

>>> isinstance(1.5, int) 
False 

>>> isinstance(1.5, (int, float)) 
True 
1

我會趕上第一ValueError(不是整數)異常,並檢查答案是可以接受的(在1,2,3)或再多問ValueError例外

def survey(): 
    print('1) Blue') 
    print('2) Red') 
    print('3) Yellow') 

    ans = 0 
    while not ans: 
     try: 
      ans = int(input('Out of these options\(1, 2, 3), which is your favourite?')) 
      if ans not in (1, 2, 3): 
       raise ValueError 
     except ValueError: 
      ans = 0 
      print("That's not an option!") 

    if ans == 1: 
     print('Nice!') 
    elif ans == 2: 
     print('Cool') 
    elif ans == 3: 
     print('Awesome!') 
    return None