Search code examples
pythonboolean-operations

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?


Solution

  • 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!