2012-11-11 129 views
-4
from sys import exit 

def answer(): 
    answer = raw_input("> ") 
    if answer == "Yes" or answer == "yes": 
     #going to next 
     joint() 
    elif answer == "No" or answer == "no": 
     print "You still have something, I know..." 
     again() 
    else: 
     fubar() 

def again(): 
    again = raw_input("> ") 
    if again == "Yes" or again == "yes": 
     #going to next 
     joint() 
    elif again == "No" or again == "no": 
     print "You still have something, I know..." 
    else: 
     fubar() 

def fuck(): 
    print "Fubar'd!" 

def joint(): 
    print "To be continue..." 

def question(): 
    print "Hi duuuude..." 
    raw_input("To say 'Hi' press Enter") 
    print "Can you help me?" 
    answer() 

question() 

嗨,你能幫我嗎?當我回答「否」時,我試圖重複「答案」功能。我想逃避功能「再次」...還有一種方法來逃避「答案==」是「或答案==」是「:」所以不管我寫大寫或小寫字母來接受答案,而不是像小菜一樣寫「是」或「是」?重複功能

+0

是什麼阻止你用'答案'試()'替換()'在' elif'部分? –

回答

3

這通常是通過一個while循環來實現的。

編輯:正如指出的那樣,雖然循環很好,清晰,並避免遞歸限制。

沒想到一個簡單的答案會產生這麼多票....

讓我們舉一個例子

while True: 
    ans = raw_input("Enter only y or n to continue").strip().lower() 
    if ans == "y": 
     print "Done!" 
     break 
    elif ans == "n": 
     print "No?" 
    else: 
     print "Not valid input." 
+1

除了更清潔之外,我認爲while循環還避免了使用遞歸可能導致的潛在的「超過最大遞歸深度」錯誤。 – DSM

1

您的問題最簡單的辦法是刪除您again功能,以及遞歸:

def answer(): 
    ans = raw_input("> ") 
    if ans == "Yes" or ans == "yes": 
     #going to next 
     joint() 
    elif ans == "No" or ans == "no": 
     print "You still have something, I know..." 
     answer() # again() 
    else: 
     fubar() 

我不得不將您的answer變量重命名爲ans,以便它不會與函數名稱發生衝突。


對於第二個問題,你想要麼:

if answer.lower() == "yes": 

if answer in ("Yes", "yes"):