Conditionals And Control Flows

Stephen Hansen me+python at ixokai.io
Wed May 4 14:54:29 EDT 2016


On Wed, May 4, 2016, at 07:41 AM, Cai Gengyang wrote:
> I am trying to understand the boolean operator "and" in Python. It is
> supposed to return "True" when the expression on both sides of "and" are
> true 

The thing is, its kinda dubious to think of 'and' as a 'boolean
operator', because once you go down that road, some people start wanting
it to be a *pure* boolean operator. Something that always returns True
or False. Instead, 'and' and 'or' return something that is true, or
something that is false. Notice the lower case. (I know the docs call
them Boolean Operations, but I still think saying 'boolean' is
unhelpful)

Python defines false things as False, None, 0 (of any numeric type), an
empty container (lists, tuples, mappings, something else that defines
__len__ and it returns 0), and instances of classes that define
__nonzero__ that return 0 or False.

Everything else is a true thing.

If you see "x and y", the rule is: if x is a false thing, it'll return
something false. As it happens, it has x handy, and since its decided x
is false, it'll return that. Therefore, "x and y" is false. If x is
true, though, it'll return y. In this case, "x and y" will be a true
thing if y is a true thing, and a false thing if y is a false thing.

As you can see, all of this logic happens without ever using True or
False. 

-- 
Stephen Hansen
  m e @ i x o k a i . i o



More information about the Python-list mailing list