玩家拿到灯泡后,“灯泡”会附加到库存中,而light_bulb变量会设置为True
。我已将print(light_bulb)
添加到代码中,一旦灯泡被取出,它实际上设置为True
。
我无法理解为什么第9行会在最后放置and not light_bulb:
时运行。代码运行的第二次,第三次或第四次,因为light_bulb
设置为True
;将评估为and not True
或and False
。这意味着第14行应该运行而不是9,对吗?
inventory = ["null"]
def lol():
choice1 = input(">")
light_bulb = False
if "bulb" in inventory:
light_bulb = True
if "bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() or "light" in choice1.lower() and not light_bulb:
inventory.append("bulb")
print("You try to fix the light bulb but it comes off. You decide to keep it.")
alley()
elif "bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() and light_bulb:
print ("You already have a light bulb!")
alley()
else:
dead("You fumble around in the darkness and accidentally kill yourself.")
答案 0 :(得分:1)
and
运算符的绑定比or
更紧密。所以你写的内容相当于:
if "bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() or ("light" in choice1.lower() and not light_bulb):
你想要的是:
if ("bulb" in choice1.lower() or "unscrew" in choice1.lower() or "lightbulb" in choice1.lower() or "light" in choice1.lower()) and not light_bulb:
要做到这一点,你需要括号。
答案 1 :(得分:1)
该问题与评估or
和and
表达式的顺序有关。 and
运算符的优先级高于其前面的or
表达式,因此首先对其进行求值。我怀疑你最后要评估它。尝试添加括号,使命令显式化(这也允许您将行包装到更合理的长度):
if ("bulb" in choice1.lower() or "unscrew" in choice1.lower() or
"lightbulb" in choice1.lower() or "light" in choice1.lower()) and not light_bulb:
请注意,检查字符串"lightbulb"
可能是不必要的,因为您还要分别检查其子字符串"light"
和"bulb"
(以及in
运算符dosn'尊重单词边界)。