Sorath
Sorath

Reputation: 553

I can't seem to break out of my While loop even when it is False?

I am writing Python code for the game Tic Tac Toe, however I have stumbled upon a hurdle already and can't seem to break out of a While loop:

print("Welcome to Tic Toe!")

Player1_Tag=input("Player 1: Choose between X and 0: ")

while Player1_Tag != "X" or Player1_Tag != "0":
    print("Invalid input")
    Player1_Tag=input("Player 1: Choose between X and 0: ")
else:
    if Player1_Tag=="X":
        Player2_Tag="0"
    else:
        Player2_Tag="X"

When I run this the program, it asks if I want to be "X" or "0" - if i choose '#' for example I get "Invalid input" and it asks me again in which case I choose "X" but it again gives me "Invalid input" and asks me again.. which is of course not what I want. I am confused as I don't understand why the loop keeps going even though I choose a valid input?

I have tried putting a "break" in the while loop but the loop breaks out if I choose an invalid input twice consecutively.. which is not what I want, I want it to ask me again for the third time, fourth time until I get it right.

Upvotes: 0

Views: 58

Answers (3)

Scott Hunter
Scott Hunter

Reputation: 49921

Player1_Tag != "X" or Player1_Tag != "0" will always be true.

Consider 3 possibilities:

  1. If Player1_Tag == "X", then Player1_Tag != "0"
  2. If Player1_Tag == "0", then Player1_Tag != "X"
  3. If Player1_Tag is anything else, it is neither "X" nor "0".

A clearer way to write this would be while Player1_Tag not in ("X","0"):

Upvotes: 1

Blckknght
Blckknght

Reputation: 104802

Your issue is caused by a logic error in the condition you're testing in your loop. You're currently testing Player1_Tag != "X" or Player1_Tag != "0", which is always True, regardless of what Player1_Tag is. If the variable is equal to one of the strings, it will be not-equal to the other. Since you're joining the two comparisons with or, you'll never exit the loop.

You need to either join the pieces of your test with and instead of or (Player1_Tag != "X" and Player1_Tag != "0"), or negate the comparisons (by changing != to ==) and do a negation of the whole expression: not (Player1_Tag == "X" or Player1_Tag == "0"). By De Morgan's laws, those are equivalent.

Upvotes: 1

Bendik Knapstad
Bendik Knapstad

Reputation: 1458

The problem is that you've used or when you should have used and

If Player1_Tag is equal to 0 It's at the same time not equal to X And or checks if either is `True'

Upvotes: 0

Related Questions