Search code examples
pythonloopswhile-looptic-tac-toe

Do while loops reset the variable in Python?


I'm new to Python, and I was following a youtube tutorial on how to make a tic-tac-toe. My code works fine, but I can't seem to understand why one section of the code works. Here's the code:

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.")

Basically, this code accepts an input from the player between 1 to 9 (which are the 9 positions in the tictactoe). It runs a while loop in order to check if it is between 1-9, and check if the player is placing their Os or Xs in a blank(-) spot. If it is not a blank, the code repeats itself.

Here's an example of what shows up when I input 8

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

Ok, I will input another 8 so it would overlap the previous X

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

However, what I can't understand is why the "position"(when it has a value between 1-9) runs the inner while loop(the one with the string list) and asks for another input. If position is a number that is between 1-9 and was just accidently placed in a non-blank space, shouldn't the inner while loop not be triggered, since it is between 1-9? I think this should just go on in an endless loop (of the outer while loop) as the position keeps subtracting itself by 1 until it is stopped by the inner while loop when it goes below "1".

Can you guys please explain why the inner while loop works and asks for an input when the position(between 1 and 9) does not meet the inner loop's conditions?

Edited: Here is how the board looks like as one of you asked:

    # 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]}')

Solution

  • The reason it works is because input() returns a string, and the if statement checks if the string input is contained in that list of strings.("8" is in ["8"]). However, after the input is given it's converted into an int and an int can't be equal to a string so it asks for another input. in this case:

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