Search code examples
pythonboolean-logicboolean-expression

Why does "test" and "test" return "test" , 1 and 1 return 1 instead of True?


Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True?

>>> 'test' and True
True
>>> True and 1
1
>>> 0 and True
0
>>> 0 and False
0
>>> 'test' and True
True
>>> 'test' and False
False
>>> 0 and True
0
>>> 0 and False
0
>>> 1 and True
True
>>> 1 and False
False
>>> [2,3] and True
True
>>> [2,3] and False
False

why doesn't it return either True or False?


Solution

  • Quoting Python documentation,

    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.

    (Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not 'foo' yields False, not ''.)

    As stated in the documentation, if the first expression is Falsy in x and y, no matter what the value of the expression y, it will be returned, similarly if the expression x is truthy then the result of the expression x is returned.

    That is why "test" and "test" gives you test. Try this,

    >>> "test1" and "test2"
    'test2'
    >>> "" and "test2"
    ''
    >>> "" or "test2"
    'test2'
    >>> "test1" or "test2"
    'test1'
    

    In "test1" and "test2" case, test1 is evaluated and it turns out to be Truthy. So, the second expression also has to be evaluated and the result of that evaluation is returned as test2.

    In the "" and "test2" case, since empty strings are Falsy, and need not have to check the second expression.

    In "" or "test2", since the empty strings are Falsy, or evaluates the next expression and returns that as the result. Hence, test2.

    In "test1" and "test2", since test1 is Truthy, or need not have to evaluate the second expression and returns test1.