let's say a='hi'
I want to know if a is any of the following 'hi', 'yes', or 'no' I could just run
a='hi'
a=='hi' or a=='yes' or a=='no'
>>>True
But let's say it is a really long list of possibilities so I just say
a='hi'
a==('hi' or 'yes')
When I do this I get the answer True But when I do something like this:
a==('yes' or 'hi')
>>>False
and then this is also weird
a==('yes' and 'hi')
>>>True
but if I switch them around again
a==('hi' and 'yes')
>>>False
Can someone explain what is happening here
The reason why some of your lines evaluate to True
while the others evaluate to False
is simply due to how and
/or
work in Python:
The expression
x and y
first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.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.
Thus, let's walk through your cases.
('hi' or 'yes')
'hi'
is truthy, so this expression evaluates to 'hi'
. a == 'hi'
evaluates to True
.
('yes' or 'hi')
Same reasoning, except now it evaluates to 'yes'
. a == 'yes'
is False
.
('yes' and 'hi')
Since 'yes'
is truthy, the expression evaluates to 'hi'
, and a == 'hi'
is True
.
('hi' and 'yes')
Finally, since this evaluates to 'yes'
, a == 'yes'
is False
.
If you want to test if a string is one of multiple things, test if it's in a set:
if a in {'hi', 'yes', 'no'}:
# Do something