Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logical paradox in python?

Tags:

python

I came over this, where "not None" equals both True and False simultaneously.

>>> not None
True

>>> not None == True
True

>>> not None == False
True

At first I expected that this would be because of the order of operators, but however when testing a similar expression:

>>> not False
True

>>> not False == False
False

>>> not False == True
True

Can anyone explain why this is happening?

like image 424
Dog eat cat world Avatar asked Jun 29 '11 11:06

Dog eat cat world


2 Answers

This is due to operator precedence. not none == True means not (None == True) means None != True, which is true. Similarly, None != False is also true. The value None is distinct from the booleans.

Your last two expressions mean False != False, which is false, and False != True, which is true.

like image 98
Fred Foo Avatar answered Sep 18 '22 23:09

Fred Foo


This is indeed due to operator precedence. not None == False will be evaluated as not (None == False). None == False is False, which explains your results.

Try this instead:

>>> (not None) == True
True
>>> (not None) == False
False
like image 26
Sven Marnach Avatar answered Sep 18 '22 23:09

Sven Marnach