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

时间:2016-04-03 15:49:45

标签: python loops user-input

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

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 循环,以便任何其他输入无效。

1 个答案:

答案 0 :(得分:1)

让我们考虑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是真的。

如果action4 = "right"怎么办?那么cond1 -> True只有cond2 -> False,所以因为其中一个是True,cond1 or cond2是真的。

我认为您需要更改的是orand,因此如果action4不是左侧或右侧的,那么它将会中断:

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

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

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

这有点容易理解。