Question About Logic In Python

Bengt Richter bokr at
Wed Sep 21 17:26:48 CEST 2005

On Wed, 21 Sep 2005 09:03:00 +1000, Steven D'Aprano <steve at> wrote:

>On Tue, 20 Sep 2005 03:03:15 +0000, Ron Adam wrote:
>> Steven D'Aprano wrote:
>>> Are there actually any usage cases for *needing* a Boolean value? Any
>>> object can be used for truth testing, eg:
>> Of course if any of the default False or True conditions are 
>> inconsistent with the logic you use, you need to do explicit truth testing.
>> So..
>>     bool(a and b) * value
>> Would return value or zero, which is usually what I want when I do this 
>> type of expression.
>That's all very interesting, and valuable advice for somebody who doesn't
>understand how Python's logical operators work, but the question is, when
>would you actually want that type of expression?
>In practice, how often do you really care that your truth values have the
>specific values 0 and 1 rather than anything false and anything true? In
>what circumstances?
When you want to use the value as an index fed to something that has a
__getitem__ for which only the values 0 and 1 are valid, e.g., a list
or tuple of length 2, as I tried to illustrate before ;-)

Also, since values 0 and 1 are the values of a bit, you can shift it
and create a mask that encodes many logical values at once, which can
be handy for truth table stuff or perhaps indexing a 2**nbits table
rather than using a tree of nested if/elses to select values.

BTW, you asked
"Are there actually any usage cases for *needing* a Boolean value?"
                    ^^^ ;-)
AFAIK, "one" is enough to make the answer "yes" ;-)

Of course you can use other expressions than bool(x) to get the boolean
value, but you may have to think more about whether (x and 1) will
do it, or whether you should write (x!=0) or, in case x can be None,
perhaps settle on (x and 1 or 0) as an idiom to play safe.
Well, bool(x) is safe, and less typing ;-) OTOH, it's not a hammer for all nails.

Bengt Richter

More information about the Python-list mailing list