我正在用Python 2.7编写一个简单的基于文本的游戏。在下面的代码中,即使用户回答了与“run”或“nothing”完全不同的内容,arrested()
函数仍然会启动。我很确定问题出在这行代码中:
if "run" or "nothing" in answer:
因为如果我只提供一个字符串,如下所示:
if "run" in answer:
程序运行得很漂亮,如果答案不包含“run”,则调用remote_spot()
。整个代码如下:
def facing_cops():
print "There are several cars that might serve as stake-outs for the cops. What do you do?"
answer = raw_input("> ")
if "run" or "nothing" in answer:
arrested("Cops got suspicious. You are arrested, along with the drug dealer.")
else:
remote_spot()
你觉得怎么回事?
谢谢,
克里斯
答案 0 :(得分:3)
or
没有做你想做的事。你写的内容与:
if "run" or ("nothing" in answer):
"运行"是一个字符串,在布尔上下文中,它被理解为True。所以你想要:
if "run" in answer or "nothing" in answer:
答案 1 :(得分:2)
运营商'in'优先于'或',以便您有效地测试if "run" or ("nothing" in answer)
。如果你只有两个,你可以写:
if "run" in answer or "nothing" in answer:
如果您有更多的关键字要测试而不是2,那么编写的内容会有点长,您可以选择此选项:
keywords = ["run","nothing","otherkeyword"]
if any(keyword in answer for keyword in keywords):