Evening all,
I'm new to programming and I am attempting to understanding while loops that are used with if/elif/else statements.
My Thought Process
The function that I have created is a part of the game Tic Tac Toe (or Noughts and Crosses). The idea behind the function is to prompt Player 1 for their symbol choice (O or X).
My logic behind the function is such that, the player will continue to be prompted (the loop) for a valid choice. Once the player has made a valid choice, the loop should end and print the player's choice.
My Question
What I don't understand is that the function only works if I include break at the end of both the IF and ELIF blocks of code. Why won't the loop break upon the user entering a valid choice?
Please see the code, written in Python, below.
Regards,
def player_input():
player1_input = str
player1_symbol = str
while player1_symbol != "X" or "O": #loop until user supplies an valid (X or O) input
player1_input = str(input("\nPlayer 1, would you like to be X or O?: ")) #prompt user for their choice
player1_symbol = player1_input #link player1_input to player1_symbol
if player1_symbol == "X": #follow this block if Player 1 selected X
print("\nPlayer 1: You are now X") #states that Player 1 is X
print("Player 2: You are now O") #states that Player 2 is now O as a result of Player 1's choice
print("IF Statement Executed") #lets me know that this block was executed
break #WHY DO I NEED THIS TO BREAK THE LOOP IF A VALID SELECTION WAS MADE?
elif player1_symbol == "O": #follow this block if Player 1 selected O
print("\nPlayer 1: You are now O") #states that Player 1 is O
print("Player 2: You are now X") #states that Player 2 is now O as a result of Player 1's choice
print("ELIF Statement Executed") #lets me know that this block was executed
break #AGAIN, WHY DO I NEED THIS TO BREAK THE LOOP IF A VALID SELECTION WAS MADE
else:
print("\nInvalid choice. Please choose X or O.") #lets Player 1 know that he needs to make a valid (X or O) input
print("ELSE Statement Executed") #lets me know that this block was executed