marsx
marsx

Reputation: 715

Python Boolean help!

I have a code like this:

if (X or Y) == ("Cat" or "Dog" or "Fish" or "Bird"):
    print X, Y

It is only working if X == "Cat". Does anyone know my mistake here?

Upvotes: 2

Views: 343

Answers (4)

Hugh Bothwell
Hugh Bothwell

Reputation: 56694

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

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613461

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!

Upvotes: 11

Sven Marnach
Sven Marnach

Reputation: 602555

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

Upvotes: 4

PrettyPrincessKitty FS
PrettyPrincessKitty FS

Reputation: 6400

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!

Upvotes: 1

Related Questions