重复一个功能

时间:2012-11-11 17:02:20

标签: python

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() 
你好,你可以帮帮我吗?当我得到回答“否”时,我试图重复“回答”功能。我想要“再次”逃避功能......还有一种方法可以逃避“回答==”是“或回答==”是“:”所以无论我写资本或小写字母接受答案而不是写一个菜鸟“是”或“是”?

2 个答案:

答案 0 :(得分:3)

这通常是通过while循环实现的。

编辑:正如所指出的,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 :(得分: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"):