Python "and" behavior

Gary Herron gherron at islandtraining.com
Thu Aug 13 20:50:42 EDT 2009


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)

Notes:

*(1)*
    These only evaluate their second argument if needed for their outcome.

*(2)*
    "not" has a lower priority than non-Boolean operators, so |not a ==
    b| is interpreted as |not (a == b)|, and |a == not b| is a syntax
    error.

------------------------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090813/8e9ef233/attachment-0001.html>


More information about the Python-list mailing list