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

How do I use "or" when comparing two strings from input()

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 个。有人可以解释这个错误是如何发生的以及我可以做些什么来解决它。

这是针对初学者的项目,但我团队的 none 可以弄清楚为什么会这样。 谢谢

andor 与英语的行为不同。如果您想了解更多信息,这里是 link:from docs

将您的条件更改为:

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

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

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

等同于

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

因为非空字符串总是 return为真。布尔语句的计算结果为:

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

or 始终使用 True return 条件。 所以代码计算为

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

要修复它,您需要做的就是将 or 放在两个布尔语句

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

和类似的

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

或者按照 SorousH Bakhiatry 的建议去做

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()

感谢您的回复和回答,您链接的内容我需要研究。 谢谢!