在我的python程序中,有时在我的if语句中只有顶部的一个工作
这是我的计划 http://ubuntuone.com/0u2NxROueIm9oLW9uQVXra
当你运行程序时,如果你向东南偏南,那么它就不起作用了 问题在于函数room4():
def room4():
"""Forest go south to small town room 1 and east to forest path room8"""
room = 4
print "Forest you can go south to small town, east to forest path, or continue to explore the forest"
cmd = raw_input('> ')
cmd = cmd.lower()
if cmd == "e" or cmd == "east" or "go east":
print room8()
if cmd == "s" or cmd == "south" or "go south":
print room1()
if cmd == "forest" or cmd == "explore" or cmd == "explore forest" or cmd == "explore the forest":
print room13()
else:
print error()
print room4()
答案 0 :(得分:5)
将来,请提供您问题中的相关代码。我想你指的是以下内容:
if cmd == "e" or cmd == "east" or "go east":
print room8()
if cmd == "s" or cmd == "south" or "go south":
print room1()
if cmd == "forest" or cmd == "explore" or cmd == "explore forest" or cmd == "explore the forest":
print room13()
else:
print error()
print room4()
您始终输入第一个if
语句的原因是您有or "go east"
而不是or cmd == "go east"
。布尔上下文中的字符串(如if
语句中)中的字符串计算为true。
您可以使用以下内容代替if cmd == "e" or cmd == "east" or cmd == "go east"
:
if cmd in {"e", "east", "go east"}:
...
如果您使用的是Python 2.6或更低版本,那么设置文字不存在,而不是{"e", "east", "go east"}
使用set(("e", "east", "go east"))
。