学习Python艰难的36代码效率

时间:2015-01-24 19:35:51

标签: python

您好,我正在学习这本书"学习Python的艰难之路"作者:Zed Shaw,我已经进行了练习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()

我想知道是否有办法让所有这些选择在一行中,如果还有什么我可以提高效率请告诉我。对于我刚接触编程这个愚蠢的问题感到抱歉。

1 个答案:

答案 0 :(得分:5)

使用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."