Python3 basics: 0, other Numeric, and None in condition

Recently, I solve competitive programming problems with Python3 and then I have tripped over the trick of this post’s title.

So I explain what does it mean.

TL;DR

  • If you handle None and numeric in one variable, please use X is None or X is not None to determine whether X is None or numeric.
  • == operator compares values and is operator compares references.

One day, this kinds of path was executed:

X = 0
purchase = None
if not purchase:
purchase = 0
# (omission of middle part)if purchase: # HERE
X = 100 # Wanted path
purchase = None # Wanted path

When HERE condition was judged, I thought purchase would be evaluated as True but wouldn’t ( X == 0 and purchase == 0 as a result).

So I examined behaviors of None and numeric in condition with something like this:

>>> if not None:
... print("not None")
...
not None
>>> if None:
... print("None")
...
>>>

None is good. My assumption was not wrong. Then what caused above consequence?

>>> if not 0:
... print("not 0")
...
not 0
>>> if 0:
... print("0")
...
>>>

OMG! How about 1 and -1 ?

>>> if not 1:
... print("not 1")
...
>>> if 1:
... print("1")
...
1
>>> if not -1:
... print("not -1")
...
>>> if -1:
... print("-1")
...
-1

1 is evaluated as well as -1.

Oops! Behaviors with 0 and others were different!

0 is evaluated as False in condition!

I thought about how do I handle these None and numeric with 0 in one variable, and remembered is operator.

>>> if 0 is None:
... print("0 is None")
...
>>>
>>> if 0 is not None:
... print("0 is not None")
...
0 is not None

Good. I wrote the first program as like this and ran it again:

X = 0
purchase = None
if not purchase:
purchase = 0
# (omission of middle part)if purchase is not None: # HERE
X = 100 # passed through
purchase = None # passed through

Yay.

BTW, what is differences between == and is ?

>>> a = []
>>> b = a.copy() # new reference
>>> if a == b:
... print("a == b")
...
a == b
>>> if a is b:
... print("a is b")
...
>>>

== compares values and is compares references.

What about None and 0 ?

>>> if None == 0:
... print("None == 0")
...
>>>
>>> if None is 0:
... print("None is 0")
...
>>>

Hm, I guess None means null, so values and references are different at all.

That’s it.
Thanks.

Open Source Software Developer