学习Python困难的方式36代码效率 - python

您好,我正在学习Zed Shaw的书“ Learn Python The Hard Way”,并且已经完成了练习36,我们使用循环和if语句从头开始纠正我们自己的游戏。

我的游戏已经完成并且正在运行,但是代码本身看起来如此混乱且效率低下。主要问题是试图获得用户的选择,并且必须为相同的单词重写相同的代码,但是要使用大写字母,例如:

    def puzzle1():
print "\"A cat had three kittens: January,March and May. What was the mother's name.\""

choice = raw_input("Mother's name?: ")
if "What" in choice:
    print "You are correct, the door opens."
    door2()
elif "what" in choice:
    print "You are correct, the door opens."
    door2()
elif "WHAT" in choice:
    print "You are correct, the door opens."
    door2()
elif "mother" in choice:
    print "Haha funny... but wrong."
    puzzle1()
else:
    print "You are not correct, try again."
    puzzle1()

我想知道是否有一种方法可以将所有这些选择集中在一起,如果还有其他我可以提高效率的方法,请告诉我。对不起这个愚蠢的问题,我是编程新手。

python大神给出的解决方案

使用str.lower并删除多个if / elif。

choice = raw_input("Mother's name?: ").lower()
if "what" in choice:
    print "You are correct, the door opens."
    door2()
elif "mother" in choice:
    print "Haha funny... but wrong."
    puzzle1()
else:
    print "You are not correct, try again."
    puzzle1()

我也将循环而不是反复调用puzzle1,例如:

while True:
    choice = raw_input("Mother's name?: ").lower()
    if "what" in choice:
        print "You are correct, the door opens."
        return door2()
    elif "mother" in choice:
        print "Haha funny... but wrong."
    else:
        print "You are not correct, try again."