比较 input() 中的两个字符串时如何使用"or"


action = input("nOption: ")
if action.lower() == "1" or "door":
if kitchen_key == 0:
typewriter("You try to wrestle the door open, you swear you could remove the door from it's hinges... ... ... ... But you fail, you dejectedly return to the kitchen.")
time.sleep(1)
kitchen_choices()
elif kitchen_key == 1:
typewriter("With your newfound key you swiftly jam the key into the hole and twist. CLUNK! The sound of being one step closer to freedom! You pull the door open and continue on your way!")
time.sleep(1)
print("proceeding to next room")
if action.lower() == "2" or "stove":
stove()

上面我要求用户输入,并根据他们键入的内容给出结果。然而,以上仅运行第一选项,因此:;你试图把门撬开,你发誓你可以把门从铰链上取下来;是我的结果,即使我按2。然而,如果我使用";以及";代替";或";它起作用,但不会像";门";或";炉子";并且只有1或2。有人能解释一下这个错误是怎么发生的吗?我能做些什么来修复它吗?

这是一个初学者项目,但我的团队中没有人能理解为什么会出现这种情况。谢谢

代码的问题在于or是一个布尔运算符。您的线路

if action.lower() == "1" or "door":

相当于

if (action.lower() == "1") or "door":

因为非空字符串总是返回true。布尔语句被评估为:

if (action.lower() == "1") or True:

并且具有True的CCD_ 2ing总是返回条件。因此代码评估为

if action.lower() == "1":

要修复它,您只需要将or放在两个布尔语句之间

if action.lower() == "1" or action.lower() == "door":

和类似的

if action.lower() == "2" or action.lower() == "stove":

或者你按照索罗斯·H·巴克蒂特里的建议做

if action.lower() in ("1", "door"):

但在我看来,这不太可读。

andor的行为与英语不同。如果你想了解更多,这里有一个链接:来自文档

将您的条件更改为:

if action.lower() in ("1", "door"):

我的解决方案是在or的另一端进行变量检查。。。

if action.lower() == "1" or action.lower() == "stairs":

以及将第二个if改为elif。。。

elif action.lower() == "2" or action.lower() == "stove": 
stove()

谢谢你的回复和回答,有些事情你联系起来了,我需要研究。谢谢

最新更新