大家好,我正在学习Zed Shaw的“以艰难的方式学习Python”这本书,我已经完成了练习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()我想知道是否有一种方法可以将所有这些选择放在一行中,如果还有其他我可以做得更有效率的事情,请告诉我。对于这个愚蠢的问题,我很抱歉,我是编程新手。
发布于 2015-01-25 03:37:24
使用str.lower并删除多个if/elif for what。
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."https://stackoverflow.com/questions/28129437
复制相似问题