我是 python 的新手,我正在尝试构建一个简单的 Tic-Tac-Tock game.When 我正在接受用户的输入,它会进入无限循环
I am new to python and I am trying to build a simple Tic-Tac-Tock game.When I am taking input from user it goes to infinity loop
def player_input():
player1=''
player2=''
while player1 != "X" or player1 !="O":
player1=input('Choose from X or O').upper()
if player1=='X':
player2 = 'O'
return (player1,player2)
elif player1=='O':
player2='X'
return (player1,player2)
当我运行时,它会进入无限循环。但是,当我将 while 循环更改为 while not(player1 =="X" or player1=="O")
时,我的代码 运行 没问题。那么有人可以解释一下我的两个 while 循环之间的区别吗?
你的条件是错误的,你基本上想要在 while 循环中直到用户输入 X 或 O。因此,这意味着:
not (player1 == "X" or player1 =="O")
如果您不熟悉布尔代数,这可能会有点混乱。基本上你有以下内容:
X and Y
,所以not (X and Y)
在逻辑上等同于not X or not Y
。在你的情况下你有:
not (player1 == "X" or player1 =="O")
逻辑上等同于:
player1 != "X" and player1 != "O"
如果你想了解更多,可以阅读De Morgan's laws
def player_input():
player1=''
player2=''
while player1 != "X" or player1 !="O":
player1=input('Choose from X or O').upper()
if player1=='X':
player2 = 'O'
return (player1,player2)
elif player1=='O':
player2='X'
return (player1,player2)
当我运行时,它会进入无限循环。但是,当我将 while 循环更改为 while not(player1 =="X" or player1=="O")
时,我的代码 运行 没问题。那么有人可以解释一下我的两个 while 循环之间的区别吗?
你的条件是错误的,你基本上想要在 while 循环中直到用户输入 X 或 O。因此,这意味着:
not (player1 == "X" or player1 =="O")
如果您不熟悉布尔代数,这可能会有点混乱。基本上你有以下内容:
X and Y
,所以not (X and Y)
在逻辑上等同于not X or not Y
。在你的情况下你有:
not (player1 == "X" or player1 =="O")
逻辑上等同于:
player1 != "X" and player1 != "O"
如果你想了解更多,可以阅读De Morgan's laws