Summary of my question: I want to get input from users, they can only answer either "X" or "O", if they answer anything else, they will be prompted the same question until they answer the acceptable "X" or "O".
My initial code:
#to initiate the variable to take in input from users
input_from_user = ""
#to take only acceptable input (X or O) from users
while input_from_user not in ("X" or "O"):
input_from_user = input("Do you want X or O?: ")
print(input_from_user)
It won't work as expected because I realized the while condition return False, so the remaining codes won't run.
So I changed to below revised code, only change the OR to COMMA inside IN operator:
#to initiate the variable to take in intput from users
input_from_user = ""
#to take only acceptable input (X or O) from users
while input_from_user not in ("X", "O"):
input_from_user = input("Do you want X or O?: ")
print(input_from_user)
It then worked as expected, but I am still confused why they produced different result?
("X" or "O")performs the logical operationoron two values,"X"and"O". Since a string that's not empty is truthy, this amounts toTrue or True, so the result isTrue.input_from_useris not in(True,)nor inTrue(a single boolean value in parentheses just resolves to the boolean value), so it never matches.You want
while input_from_user not in "XO", orwhile input_from_user not in ("X", "O").You can use
into check if one string is in a string, or to check if an object is in an iterable (like the tuple).