Search code examples
pythonbooleanboolean-logicboolean-expressionboolean-operations

Python : Why does False or 'name' returns 'name' and not False?


AFAIK :

and, or are boolean operators and any boolean expression should return a boolean.

So, why does this happens :

  • False or 'name' returns 'name' and not True
  • True and '' returns '' and not False

Please explain, how does python handles boolean expressions ?


Solution

  • No, in python the or and and operations short circuit and return the last evaluated item.

    See Boolean operations:

    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.

    If you must have a boolean value, use bool():

    >>> bool(False or 'name')
    True