What is the difference between using COMMA and OR inside IN operator in python?

145 Views Asked by At

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?

4

There are 4 best solutions below

0
Grismar On

("X" or "O") performs the logical operation or on two values, "X" and "O". Since a string that's not empty is truthy, this amounts to True or True, so the result is True.

input_from_user is not in (True,) nor in True (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", or while input_from_user not in ("X", "O").

You can use in to check if one string is in a string, or to check if an object is in an iterable (like the tuple).

0
SkyPlayX On

The or keyword checks two expressions and resolves to True if atleast one of the expressions resolves to True. The first piece of code actually resolves to in (True/False) and the second one checks to see if a value is inside a tuple.

0
Polydynamical On

The "X or O" is a conditional statement which is evaluated to "X". On the other hand, your second code block checks if the input is not in the given tuple. A tuple is comma delimited list, similar to an array.

0
adrianop01 On

in your first case ("X" or "O") will always return "X". It is because a non-empty string will have True as its Truth value. Unfortunately, only @Polydynamical 's answer is correct. From https://docs.python.org/3/reference/expressions.html#or

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.