Python 如果是变量!=&引用;“字符串”;或变量!=&引用;字符串“U 2”;总是计算相同的值。从不去别的地方
我对以下代码的理解是,如果用户输入不等于“向上”或“向下”,它应该继续循环。但如果它确实等于“向上”或“向下”,那么它会将valid_move更改为True并停止循环。但不管用户输入是什么,它总是打印(“无效条目”),并且永远不会退出while循环Python 如果是变量!=&引用;“字符串”;或变量!=&引用;字符串“U 2”;总是计算相同的值。从不去别的地方,python,if-statement,conditional-statements,Python,If Statement,Conditional Statements,我对以下代码的理解是,如果用户输入不等于“向上”或“向下”,它应该继续循环。但如果它确实等于“向上”或“向下”,那么它会将valid_move更改为True并停止循环。但不管用户输入是什么,它总是打印(“无效条目”),并且永远不会退出while循环 valid_move = False while not valid_move: user_input = input("enter up or down") if user_input != "up" or user_in
valid_move = False
while not valid_move:
user_input = input("enter up or down")
if user_input != "up" or user_input != "down"):
print("invalid entry")
else:
valid_move = True
print(user_input)
为什么会这样?错误在于你的状况,而不是:
if user_input != "up" or user_input != "down")
使用:
如
或
->和
所述,如果用户输入不在('up'、'down')中,则在if语句中使用“and”而不是“or”
。
…
if user_input != "up" and user_input != "down")