I have a code like this:
if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"):
print X, Y
It is only working开发者_C百科 if X == "Cat"
. Does anyone know my mistake here?
I think you want logic like this:
animals = ["Cat", "Dog", "Fish", "Bird"]
if X in animals or Y in animals:
print X, Y
In your code the expression ("Cat" or "Dog" or "Fish" or "Bird") is treated as a logical expression which I'm sure you don't want. As it happens this expression evaluates to "Cat" which explains your observed behaviour.
>>> 'cat' or 'dog'
'cat'
>>> 'cat' and 'dog'
'dog'
These are logical operations on strings. Non-empty strings are regarded as True values. Empty strings are regarded as False. Python's logical operators return values of the same type as the operands (assuming both operands are the same type). Short-circuit evaluation explains the behaviour for or
and and
here.
In any case, it makes very little sense to perform logical operations on strings!
The or
operator in Python returns its first argument if it is "trucy", or its second argument else. The right-hand side of your comparison always evaluates to "Cat"
, and the left-hand side to X
as long as X
is "trucy".
The most concise way to get the logic you are looking for is
if set((X, Y)) & set(("Cat", "Dog", "Fish", "Bird")):
# whatever
What happens is you are working out X or Y
, giving you just X
. Then, you're working out Cat or Dog or..
, giving you just Cat
, since it's non-0.
What you want is:
if X in ("Cat","Dog", "Fish", "Bird") or Y in ("Cat","Dog", "Fish", "Bird"):
#taa daa!
Your problem is in the way Python evaluates or
. If a is truthy (not-zero, or a non-empty string, or an object) a or b
returns a; otherwise it returns b. So "string" or b
will always evaluate to "string"
.
So "Cat" or "Dog" or "Fish" or "Bird"
will always evaluate to "Cat"
,
and X or Y
will always evaluate to X
(so long as X is a string of one or more characters)
and X=="Cat"
is obviously only true when X is "Cat".
animals = set(["Cat","Dog","Fish","Bird"])
if X in animals or Y in animals:
print X, Y
精彩评论