while 循环会重置 Python 中的变量吗?

Do while loops reset the variable in Python?

我是 Python 的新手,我正在关注有关如何制作井字游戏的 youtube 教程。我的代码工作正常,但我似乎无法理解为什么代码的一部分工作。这是代码:

print(player + "'s turn.")
position = input("Choose a position from 1-9: ")

valid = False
while not valid:
    while position not in ["1", "2", "3", "4", "5", "6", "7", "8", "9"]:
        position = input("Choose a position from 1-9: ")

    position = int(position) - 1

    if board[position] == "-":
        valid = True
    else:
        print("You can't go there. Go again.")

基本上,此代码接受玩家在 1 到 9(即井字中的 9 个位置)之间的输入。它运行一个 while 循环以检查它是否在 1-9 之间,并检查玩家是否将他们的 Os 或 X 放在空白 (-) 位置。如果不是空白,代码会重复。

这是我输入 8 时显示的示例

- | - | -
- | - | -
- | - | -
X's turn.
Choose a position from 1-9: 8
- | - | -
- | - | -
- | X | -
O's turn.
Choose a position from 1-9: 

好的,我将输入另一个 8,这样它就会与之前的 X 重叠

You can't go there. Go again.
Choose a position from 1-9: 

但是,我无法理解的是为什么“位置”(当它的值介于 1-9 之间时)运行内部 while 循环(带有字符串列表的循环)并要求另一个输入。如果 position 是一个介于 1-9 之间的数字,并且只是意外地放在一个非空白 space 中,难道不应该触发内部 while 循环吗,因为它介于 1-9 之间?我认为这应该在(外部 while 循环的)无限循环中继续进行,因为位置不断减去 1,直到它在低于“1”时被内部 while 循环停止。

你们能解释一下为什么当位置(1 到 9 之间)不满足内循环的条件时,内部 while 循环会工作并要求输入吗?

已编辑: 这是你们中的一位问的董事会的样子:

    # Game Board
board = ["-", "-", "-",
         "-", "-", "-",
         "-", "-", "-"]

# Display board
def display_board():
    print(f'{board[0]} | {board[1]} | {board[2]}')
    print(f'{board[3]} | {board[4]} | {board[5]}')
    print(f'{board[6]} | {board[7]} | {board[8]}')

它起作用的原因是因为 input() returns 一个字符串,if 语句检查字符串输入是否包含在该字符串列表中。(“8”在 [“8”] ).但是,在给出输入后,它被转换为 int 并且 int 不能等于字符串,因此它要求另一个输入。 在这种情况下:

position="8"
position = int("8")-1 = 8-1 = 7
...
if 7 not in ["1",.."9"]: #And it isn't
    #ask for another input

与位置变量的数据类型有关。代码非常混乱,因为它不断从 str 到 int 反复变化,反之亦然。当您尝试重新输入 8 作为轮到 O 的输入时,它会进入外循环,从“8”变为 7(int)。它到达 else 块并打印错误消息。变量 'valid' 仍然是 False,我们进入外循环的下一次迭代。至关重要的是,数据类型 仍然是 int 并且 int 值 不会是 'in' 由字符串元素组成的列表,因此我们可以进入提示玩家进行新输入的内部循环。

在我看来,最好将 position 保留为 int 变量。