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

Luke Paireepinart rabidpoobear at gmail.com
Mon Oct 5 21:56:11 CEST 2009


On Mon, Oct 5, 2009 at 9:28 PM, Sander Sweers <sander.sweers at gmail.com>wrote:

>
> Hi Tutors,
>
> I am going through someone's python script and I am seeing a lot of the
> following boolean checks.
>
> if not s == ""
>
> if not n == 0
>
> if b == True
>
> if not b == True
>
> etc..
>
> All of these can be written without the == notation like "if n", "if s"
>

No, they cannot.  Some of them can be, others cannot.
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.

The same is true for
if not s == ""

> Now in this case where it is only used as boolean checks which would be
> the most pythonic way if writing these checks?
>
If you're sure they're boolean checks, "if n:" or "if not n:" is usually how
I see it written.
Whoever wrote your code probably thinks he knows the types of the variables
beforehand so he's just making assumptions as to whether a variable is an
int / string / etc. So you can probably safely assume that they're boolean
checks, but I take no responsibility if you break something :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091005/db9971a1/attachment.htm>


More information about the Tutor mailing list