Drake's Weblog

2 minute read

Interesting subsequent comparison:

>>> a = 1
>>> b = 10
>>> c = 100
>>> a < b < c
True
>>> (a < b) < c
True

The following 2 code snippets are equal, which can explain why the above code works in that way.

if a < b < c:
    doSomething()

if (a < b) and (b < c):
    doSomething()

How about booleans? Is True bigger than False?

>>> True < c
True
>>> True > c
False
>>> False < True
True
>>> False > True
False

And I just noticed that True / False are 1 / 0 in one implementation of CPython 2.5?! According to official document, the True & False are special type called “bool” which should not be used to compare against other type.

>>> False == 0
True
>>> True == 1
True
>>> True == 2
False
>>> False == 2
False

How about is?

>>> None is None is None
True
>>> (None is None) is None
False
>>> None is (None is None)
False

Because is is also a comparison (not a binary operator)!!! It might be not that intuitive to figure out this situation especially when you are programming some logical expression with if.

Let’s do play again True and False and I believe this time you can get it through.

>>> True is True is True
True
>>> False is False
True
>>> (False is False) is False
False

Check this if you wanna get more idea about Python’s expression.

comments powered by Disqus

Recent posts

Categories

About

You're looking at Drake's words or statements. All opinions are my own.