[Pythonmac-SIG] If/else vs or

Zachary Pincus zachary.pincus at yale.edu
Thu Oct 28 17:20:26 CEST 2010


On Oct 28, 2010, at 11:08 AM, Ronald Oussoren wrote:

>
> On 28 Oct, 2010, at 16:21, Dan Ross wrote:
>
>> I don't think this is Mac specific, but I wonder if someone could  
>> explain why these two groups of code behave differently:
>>
>> [code]
>>
>> colors = ['red', 'green', 'blue', 'orange', 'fuscia', 'black',  
>> 'white']
>>
>> list_of_matches = []
>> for x in colors:
>>     if x == 'red' or 'green' or 'blue':
>>
>
> This parses as:
>
> 	if x == ('red' or 'green' or blue'):

This would always lead to the if-test failing: ('red' or 'green' or  
'blue') evaluates to True, and x != True. What's observed is the if- 
test always passing... As the equality operator is higher-precedence  
than boolean operators, and equal precedence operators group left-to- 
right, the above parses as:
     if (((x == 'red') or 'green') or 'blue'):

noting that non-empty strings (like 'green') evaluate as True in an if- 
test, this will test if x == 'red', and if not, it will go on to  
testing if 'green' evaluates to True (which it does), and so forth.

Dan, you could fix your code as:
     if x == 'red' or x == 'green' or x == 'blue':

But this is better:
     if x in ('red', 'green', 'blue'):

and this scales best:
     good_colors = set(['red', 'green', 'blue'])
     if x in good_colors:


Zach






> Ronald
> _______________________________________________
> Pythonmac-SIG maillist  -  Pythonmac-SIG at python.org
> http://mail.python.org/mailman/listinfo/pythonmac-sig
> unsubscribe: http://mail.python.org/mailman/options/Pythonmac-SIG



More information about the Pythonmac-SIG mailing list