KeyError与有效密钥

时间:2012-10-14 02:06:25

标签: python dictionary

    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。

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

1 个答案:

答案 0 :(得分: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)