首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过艰苦的方式学习Python 36代码效率

通过艰苦的方式学习Python 36代码效率
EN

Stack Overflow用户
提问于 2015-01-25 03:35:51
回答 1查看 144关注 0票数 2

大家好,我正在学习Zed Shaw的“以艰难的方式学习Python”这本书,我已经完成了练习36,我们使用循环和if语句从头开始修改我们自己的游戏。

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

代码语言:javascript
复制
    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()

我想知道是否有一种方法可以将所有这些选择放在一行中,如果还有其他我可以做得更有效率的事情,请告诉我。对于这个愚蠢的问题,我很抱歉,我是编程新手。

EN

回答 1

Stack Overflow用户

发布于 2015-01-25 03:37:24

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

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
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."
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28129437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档