[Tutor] if n == 0 vs if not n

Dave Angel davea at ieee.org
Tue Oct 6 16:58:58 CEST 2009


Wayne wrote:
> On Mon, Oct 5, 2009 at 3:37 PM, Sander Sweers <sander.sweers at gmail.com>wrote:
>
>   
>> Thanks Wesly/Vern for the replies.
>>
>> On Mon, 2009-10-05 at 21:56 +0200, Luke Paireepinart wrote:
>>     
>>>         if not n == 0
>>>
>>> if b == True can be written as if b.
>>>
>>>
>>> However,
>>> if not n == 0 can be written as if n != 0 but NOT as if n.
>>> The reason why is that 0 is not equivalent to False even though it
>>> evaluates to False.
>>> So
>>> if not n:
>>> would be true for n = 0 and for n = "" and for n = None
>>> but
>>> if n != 0:
>>> would be true for n = "" and n = None but not n = 0.
>>>       
>> Ah, have not thought about this one. In this case it checks the return
>> code of a subprocess command which if not zero means build failure. I am
>> leaving these as they are because in my opinion "if not returncode == 0"
>> shows clearer what is going on than "if returncode".
>>
>>     
>
> If it's checking the returncode against a value, Vern makes a good point:
>
> if returncode != 0 makes a whole lot more sense than "if not returncode ==
> 0"
>
> Though when dealing with an integer return code, doesn't it make more sense
> to use the "is" operator?
>
> if returncode is 0:
>     #do something
>
> if returncode is not 0:
>     #do something
>
> -Wayne
>
>   
No, because you're not assured that all integers that are equal are the 
same object.  Python optimizes that for small integers, but there's no 
documented range that you can count on it.

 >>> x = 374
 >>> y = 374
 >>> print id(x), id(y)
12721272 12721296
 >>> x==y
True
 >>> x is y
False

DaveA



More information about the Tutor mailing list