0
    def askme(answers):
            question = raw_input("Do you want to see my name, age or favorite fruit?\n")
            if not question in answers:
                    print "I have no answer for that, ask something else"
                    askme(answers)
            answer_to_question = answers[question]
            return answer_to_question

    answers = {"name":"John", "age":18, "fruit":"apple"}

    while True:
            answer_to_question = askme(answers)
            print "Answer is %s" % answer_to_question

我希望它如何运行:如果输入不在字典中,则要求新输入 如果输入在字典中,则使用输入作为键

出了什么问题:在我传入一个不在键中的值后,它要求我提供新的输入。如果我传入一个键中的值,我会得到一个 KeyError。

为什么会发生这种情况,我该如何解决?

4

1 回答 1

0

问题是因为你在递归。当提出一个无效问题时,程序会正确通知并递归,但在找到答案后,它会从中断的地方重新开始。

我认为最好的解决方法是更改​​函数的顶部以避免递归:

question = raw_input("Do you want to see my name, age or favorite fruit?\n")
while not question in answers:
    print "I have no answer for that, ask something else"
    question = raw_input("Please type 'name', 'age' or 'fruit'.\n")

另一种解决方法是保留递归格式,但如果提出的问题无效,则阻止程序从中断的地方恢复。在这种情况下,您只需要将递归调用替换为:

return askme(answers)
于 2012-10-14T02:16:48.967 回答