Python "and" behavior

Ethan Furman ethan at stoneleaf.us
Fri Aug 14 10:04:14 EDT 2009


MRAB wrote:
> Gary Herron wrote:
> 
>> goldtech wrote:
>>
>>> 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.
>>> Thanks.
>>>
>>>
>>>  
>>>
>>>>>> ss=1 and "fffff"
>>>>>> ss
>>>>>>         
>>>
>>> 'fffff'
>>>  
>>>
>>>>>> ss=0 and "fffff"
>>>>>> ss
>>>>>>         
>>>
>>> 0
>>>   
>>
>>
>> Python's Boolean operators don't turn arbitrary values into True and 
>> False values.  If you use it in any conditional, you'll get the same 
>> result as if it did, but it is occasionally it's nice to get the 
>> actual values used in the "and" instead of having the value distilled 
>> down to a True/False.
>>
>>
>>  >From the Python manual:
>> These are the Boolean operations, ordered by ascending priority:
>>
>> Operation     Result     Notes
>> |x or y|     if x is false, then y, else x     (1)
>> |x and y|     if x is false, then x, else y     (1)
>> |not x|     if x is false, then |True|, else |False|     (2)
>>
> The Pythonic table would be:
> 
> Operation     Result
> |x or y|     x if x else y
> |x and y|     y if x else x
> |not x|     False if x else False
> 
> :-)

That last should be
|not x|   False if x else True

~Ethan~



More information about the Python-list mailing list