Search code examples
python-3.xtic-tac-toe

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)

When I am running it is going to infinity loop. But,when I am changing my while loop to while not(player1 =="X" or player1=="O") my code is running fine. So can someone explain the difference between my both while loop?


Solution

  • Your condition is wrong, you basically want to be in the while loop until the user enters either X or O. Thus, this means:

    not (player1 == "X" or player1 =="O")
    

    This might be a bit confusing specially if you are not familiar with boolean algebra. Basically you have the following:

    X and Y, so not (X and Y) is logically equivalent to not X or not Y. In your case you have:

    not (player1 == "X" or player1 =="O")
    

    which is logically equivalent to:

    player1 != "X" and player1 != "O"
    

    If you want to know more about this, you can read about De Morgan's laws