2013-10-16 94 views
0

我不知道爲什麼我從來沒有想過這個......但我想知道是否有一個整理/更短/更有效的錯誤處理用戶輸入的方式。例如,如果我要求用戶輸入「hello」或「goodbye」,並輸入其他內容,我需要它告訴用戶它是錯的,然後再詢問。Python用戶輸入錯誤處理

對於所有的編碼是我做過的,這是多麼我已經做到了(通常的問題是更好):

choice = raw_input("hello, goodbye, hey, or laters? ") 

while choice not in ("hello","goodbye","hey","laters"): 

    print "You typed something wrong!" 

    choice = raw_input("hello,goodbye,hey,or laters? ") 

是否有這樣做的一個更聰明的方式?或者我應該堅持自己的方式?這是我用我寫了一首歌。

感謝所有語言的方法,

肖恩

回答

4

做到這一點對於一個簡單的腳本,你有它的方式是好的。

對於更復雜的系統,您可以有效地編寫自己的解析器。

def get_choice(choices): 
    choice = "" 
    while choice not in choices: 
     choice = raw_input("Choose one of [%s]:" % ", ".join(choices)) 
    return choice 

choice = get_choice(["hello", "goodbye", "hey", "laters"]) 
+0

我喜歡這個,因爲它是一般的,並且提示是基於選擇自動生成的。我唯一的批評就是我會'',''加入(選擇)'而不是''「.join(選擇)'。而且我也會在選擇時不選擇:' – SethMMorton

+0

嗯。我可以看到創建一個更清潔的方法,但我覺得我更喜歡它的唯一方法是如果我將一個函數傳遞給它,以便我可以使用該方法來處理每個問題。這肯定是方便的,只是...它可能需要我花一點時間來找出並替換大聲笑 – user2869231

+0

因爲,我有很多的用戶輸入,所以我寧願沒有每個人的新方法 – user2869231

0

這是你怎麼做。 根據你的使用方式,讓列表中的選項可能更漂亮。

options = ["hello", "goodbye", "hey", "laters"] 
while choice not in options: 
    print "You typed something wrong!" 
+0

不要以爲它是特別「漂亮」,但我想這是一個品味問題。不過,我喜歡你只構造一次列表/元組。 – Jblasco

+0

@Jblasco它在很大程度上取決於選項的數量。 – Mattias

+0

對不起,@Mattias,完全誤讀你的答案!我以爲你打算說一個列表比一個元組更漂亮!然後,爲了讓事情變得更加複雜,我去了,並且說我確實喜歡你將這些選項分開...... xD – Jblasco

0

如果您修改代碼以始終進入while循環,你只需要對一個行raw_input

while True: 
    choice = raw_input("hello, goodbye, hey, or laters? ") 
    if choice in ("hello","goodbye","hey","laters"): 
     break 
    else: 
     print "You typed something wrong!" 
+0

的確如此。如果代碼中沒有第二行代碼 – user2869231

1

你可以用遞歸

>>> possible = ["hello","goodbye","hey"] 
>>> def ask(): 
...  choice = raw_input("hello,goodbye,hey,or laters? ") 
...  if not choice in possible: 
...   return ask() 
...  return choice 
... 
>>> ask() 
hello,goodbye,hey,or laters? d 
hello,goodbye,hey,or laters? d 
hello,goodbye,hey,or laters? d 
hello,goodbye,hey,or laters? hello 
'hello' 
>>> 
+0

,它可能會使事情變得更漂亮如果用戶不知道如何輸入正確的輸入,是否會有達到最大遞歸限制的風險? – SethMMorton

+0

是的,這就是爲什麼通常你讓用戶知道。 –

+0

它似乎也會起反作用;使它更長,更復雜大聲笑 – user2869231