Python:如何编码 2 个不同的输入

Python: How to code 2 different inputs

我正在尝试制作一款游戏来学习如何使用 python 进行编码。如果用户输入无效,我已经达到了我想要 while 循环继续请求输入的部分。但我也想要两个不同的输入来提供不同的输出。但是,我已经对其进行了编码,因此任何用户输入都是无效的。

action4 = input()
while action4 != ("left") or action4 != ("right"):                           
    print ("Left or right?")
    action4 = input()
if action4 == ("left"):
    print ("You turn left and proceed down this hallway")
    left = True
elif action4 == ("right"):
    print ("You turn right and proceed down this hallway")
    left = False

我正在努力使 leftright 都是有效输出。但保留 while 循环,以便如果任何其他输入无效。

让我们考虑一下 while 循环中的条件:

action4 != ("left") or action4 != ("right")

我们需要将其计算为 False 以跳出 while 循环,那么什么值会使它变为 False?我们可以像这样分解条件:

action4 = ...
cond1 = action4 != ("left")
cond2 = action4 != ("right")
result = cond1 or cond2
print(cond1,cond2,result)

那如果action4 = "left"呢?那么 cond1 -> False 但是 cond2 -> True 所以因为其中一个是 True,所以 cond1 or cond2 是 True。

如果action4 = "right"呢?那么 cond1 -> True 但是 cond2 -> False 所以因为其中一个是 True,所以 cond1 or cond2 是 True。

我认为你需要改变的是 orand,所以如果 action4 不是 或者 的 left 或 right 那么它就会中断:

while action4 != ("left") and action4 != ("right"):

或者您可以使用 not in 运算符:

while action4 not in ("left","right"):

这样比较容易理解。