Python "and" behavior

MRAB python at mrabarnett.plus.com
Thu Aug 13 21:09:09 EDT 2009


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

:-)



More information about the Python-list mailing list