Question About Logic In Python

Ron Adam rrr at
Tue Sep 20 05:03:15 CEST 2005

Steven D'Aprano wrote:

> On Mon, 19 Sep 2005 12:16:15 +0200, sven wrote:
>>to make sure that an operation yields a boolean value wrap a bool() 
>>around an expression.
>>None, 0 and objects which's len is 0 yield False.
>>so you can also do stuff like that:
> Are there actually any usage cases for *needing* a Boolean value? Any
> object can be used for truth testing, eg:
> if the_str
> is to be preferred over:
> if bool(the_str)
> or even worse:
> if bool(the_str != "")
> Or wait, I have thought of one usage case: if you are returning a value
> that you know will be used only as a flag, you should convert it into a
> bool. Are there any other uses for bool()?

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.

     if val > -1:

Where 0 would be True condition.

     if arg != None:

Where '' could be a True condition.

Also...  you need to be careful what order you do your comparisons in as..

     (1 and 2) != (2 and 1)  # they are both True, but not equal.

     bool(1 and 2) == bool(2 and 1)

     (1 and 2) * value  !=  (2 and 1) * value
     # except if value is False.

     bool(1 and 2) * value == bool(2 and 1) * value


    bool(a and b) * value

Would return value or zero, which is usually what I want when I do this 
type of expression.


More information about the Python-list mailing list