2012-08-25 24 views
1

我試圖讓用戶輸入一個特定的單詞。Python:檢查用戶對raw_input的迴應()

我的代碼:

import os 

os.system("clear") 

def get_answer(): 
    print "\nWould you like to 'hit', 'stick', 'double' down or 'split'?" 
    x = raw_input('> ') 
    answers = ['hit', 'stick', 'double', 'split'] 
    y = [i for i in answers if i in x] 
    if y == []: 
     get_answer() 
    print y 
    # exit(0) 
    return y 

def foo(): 
    a = get_answer() 
    print a 

foo() 

這裏是我的輸出,如果我回答「打」的第一次;

Would you like to 'hit', 'stick', 'double' down or 'split'? 
> hit 
['hit'] 
['hit'] 

這裏是我的輸出,如果我輸入「嗒嗒」拳頭時間,然後「重災區」:

Would you like to 'hit', 'stick', 'double' down or 'split'? 
> blah 

Would you like to 'hit', 'stick', 'double' down or 'split'? 
> hit 
['hit'] 
[] 
[] 

我甚至不真正懂得研究這個。這是一個簡單的語法錯誤還是有一個更深的問題,我只是不明白?我很想知道如何正確地做到這一點。

+0

的['cmd'(http://docs.python.org/library/cmd.html)模塊可能是你想要什麼 – JBernardo

回答

4

你想簡單地測試if x in answers,它檢查輸入是否是answers中的一個元素。

此外,由於您正在使用遞歸獲取用戶的輸入,因此輸入不正確的值會將另一個get_answer()調用放在堆棧上。結果是,在最內層get_answer獲得有效輸入時,外部get_answer調用繼續執行,導致您看到奇怪的輸出。

例如,在第二個情況下,通過最裏面的呼叫的print y產生['hit'],由外呼叫的print y(由於內get_answer飾面)產生的第一[],並且通過在foo()print a(生成的最後[]因爲外部get_answer返回[])。

你可能想要做的,而不是什麼是(a)改變get_answer調用return get_answer()這樣最來電的價值被髮回的堆棧,或(b)改變get_answer調用一個循環,並打破了當你得到一個很好的答案。

假設你正在試圖獲得用戶輸入的選項只有一個,這就是你如何構建代碼使用遞歸的循環,而不是:

def get_answer(): 
    answers = ['hit', 'stick', 'double', 'split'] 
    while True: 
     print "\nWould you like to 'hit', 'stick', 'double' down or 'split'?" 
     answer = raw_input('> ') 
     if answer in answers: 
      return answer 

print get_answer() 
+0

非常感謝您的詳細解答!然而,一個代碼示例將不勝感激,因爲我試圖採用您的建議,我也遇到了同樣的問題。 – dwstein

+0

感謝您添加示例! – dwstein

0

的問題是更根本的一點。在get_answer()功能,從自身內部調用該函數你recurse

if y == []: 
    get_answer() 

雖然這個工程,我懷疑這是你的預期行爲。您必須撥打get_answer()以外的get_answer(),以便很好地提示值。

不管怎麼說,這裏的我會怎樣構建你的代碼:

def get_answer(question, answers): 
    response = raw_input(question) 

    while response not in answers: 
     response = raw_input(question) 

    return response 

if __name__ == '__main__': 
    question = "Would you like to 'hit', 'stick', 'double' down or 'split'?\n> " 
    answers = ['hit', 'stick', 'double', 'split'] 

    print get_answer(question, answers) 
+0

好吧,不完全正確。如果你做'如果y == []:return get_answer()'它實際上工作正常(除非用戶輸入錯誤的東西1000次,並得到堆棧溢出...) – nneonneo

+0

如果函數達到最大遞歸深度,Python只會拋出一個'RuntimeError'。在這種情況下,我不建議使用遞歸,因爲它不是必需的。 – Blender