0

I'm on my first Python project trying to create a tic-tac-toe game. I have a question regarding while loop logic. So I have a player input function, whereby the player decides what marker (X or O) in tic-tac-toe they would like to play with.

My function is as follows:

def player_input():
    marker = ''
    
    while marker != 'X' or  marker != 'O':
        marker = input('Player 1 choose X or O ').upper()
        
    if marker == 'X':
        return ('X','O')
    else:
        return ('O','X')

The result is the while loop continues to ask the user the question even if they give the correct input ('X' or 'O')

However, upon checking the solution, this modification to the while loop statement returns the tuple corresponding to the marker the user entered:

while not (marker == 'X' or marker == 'O'):

I don't understand how this works, From my perspective I have written the exact same thing above in the player_input function, am I missing something really obvious?

STerliakov
  • 4,983
  • 3
  • 15
  • 37
Alex
  • 1
  • 1
  • `while marker != 'X' or marker != 'O':` -> `while marker != 'X' and marker != 'O':` If it's 'X' then it's not 'O', and vice versa, so the `or` condition is always met – G. Anderson May 23 '23 at 22:35
  • `not (A or B)` is equivalent to `(not A) and (not B)`, negation is not distributive over conjunction or disjunction. – STerliakov May 23 '23 at 22:43

2 Answers2

1

Your Logic will never leave the while statement as both truth statements, marker != 'X' and marker != 'O', cannot be both False at the same time. If you entered 'x' or 'X' the marker marker != 'O' statement would be True and vice versa, causing the while loop to repeat.

You could instead use while marker != 'X' and marker != 'O':, which will move on when your input is either X or O.

-1

We can try every case scenario to understand the case.

Let's say user type a.

marker != 'O' or marker != 'X'

Both expressions, right and left will be true since marker is different than O and X. True or True = True. The loop continue.

Let's say user type X.

marker != 'X' or marker != 'O'

The first expression will be true, the second false. True or False = True Your while loop will keep going asking.

Let's say user type O.

 marker != 'X' or marker != 'O'

The second expression will be True, the first false. False or True = True The loop will keep going.

The only way to stop the loop is for marker to be X and O at the same time. Both expression would evaluation to False. False or False = False. But it is impossible in your case. When you use !=, the expression is True when marker is different than X or O. It is False when it is equal. See the picture for a summary of boolean logic. It's always nice to have one next to you to remember. After a while, it becomes natural.

enter image description here