0

In my program encountered with this:

>>> True and True and (3 or True)
3

>>> True and True and ('asd' or True)
'asd'

while I expected to get some boolean value depending on the result in brackets. So if I try comparisons like these (0 or True) or ('' or True) python will return True, which is clear because 0 and '' equivalent to False in comparisons.

Why doesn't python return boolean value by converting 3 and 'asd' into True?

AmirM
  • 1,089
  • 1
  • 12
  • 26
  • Are you asking *what* `and` does, or why it *doesn't* automatically convert its result to a boolean? – user2357112 Jun 30 '16 at 22:25
  • Also, putting in `(0 or True)` or `('' or True)` wouldn't have given you `False`. You would have gotten `True`. – user2357112 Jun 30 '16 at 22:26
  • @user2357112 yes, my silly mistake. Updated. Regarding question - I was a bit confused how to set it right. But the answer below clarifies this thing anyway – AmirM Jun 30 '16 at 22:33

1 Answers1

4

From https://docs.python.org/3/library/stdtypes.html:

Important exception: the Boolean operations or and and always return one of their operands

The behavior can be most easily seen with:

>>> 3 and True
True

>>> True and 3
3

If you need to eliminate this behavior, wrap it in a bool:

>>> bool(True and 3)
True

See this question

As Reut Sharabani, answered, this behavior allows useful things like:

>>> my_list = []
>>> print (my_list or "no values")
Community
  • 1
  • 1
sheridp
  • 1,386
  • 1
  • 11
  • 24
  • 1
    Other surprising and silly things: Thanks to inefficiencies in builtin name lookup and function calls compared to syntax based operations, `not not x` is a faster way of converting from truthy/falsy to `True` and `False` than `bool(x)`. Not that I actually recommend that, unless you're really pressed for cycles and it's the hottest part of your code. The fastest solution is just using the truthy and falsy value directly without converting. – ShadowRanger Jun 30 '16 at 23:41