Python "and" behavior
apt.shansen at gmail.com
Fri Aug 14 03:02:38 CEST 2009
> Could you explain or link me to an explanation of this? Been using
> Python for a while but not sure I understand what's happening below.
> >>> ss=1 and "fffff"
> >>> ss
> >>> ss=0 and "fffff"
> >>> ss
The "and" and "or" operators in Python are actually not true boolean
operators: they operate on the more fundamental interpretation of Truth that
Python uses (and that 'if' for example uses) that goes back before Python
got actual boolean True/False values.
"x and y" evaluates first x; if it is false, its value is returned.
Otherwise, the value of y is returned.
"x or y" evaluates first x; if it is true, its value is returned. Otherwise,
the value of y is returned.
Python's idea of "true" verses "false" isn't the same as True and False.
It's been described as "something" verses "nothing", as in Python the
following are considered false: False, None, numeric 0 (in all types of
numbers), empty strings, empty containers (lists, tuples, dictionaries,
sets). Everything else is True. Instances of any class are True by default,
but they can have a __nonzero__ operation on them to override that.
So, every value has an innate 'truthfulness' about it: the 'if' statement
bases its decision on that truthfulness. In the context of truthfulness, the
string "hello" is just as true as the singleton True. So, if you do "x and
y", if 'x' is a false value... then 'x' is returned-- as 'x' is just as
false as the singleton False. Both are different ways of saying 'false' in
Lots of people don't like this. Lots of people do. Some people want it to be
pure-true boolean algebra, have them return True/False always-- some people
have even argued for "if" only branching on True/False values. The fact of
the matter is, this is all just a fundamental part of Python that pre-dates
it ever having true boolean values, and is never gonna go away.
There's some useful properties to it, like:
value = opt or "default"
In this case, if opt was set to a something, it'll end up in value.
Otherwise, "default" will. Of course that's only useful where a opt would
never have a blank string or 0 or such in it naturally.
The poor-man's ternary operator was commonly used before Python got a proper
value = x and "Yes" or "No"
The construct had some limits(namely, the value in the "Yes" part of the
expression must be truthy), but is still useful in a lot of situations. If
"x" would evaluate true, then value would be set to "Yes". Otherwise, it'd
be set to "No".
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list