Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"2+2=5" Python edition

Can somebody explain this tricky output:

>>> not(type(1.01)) == type(1) # Why does the expression evaluates to True!?
True
>>> not(type(1.01))
False
>>> False == type(1)
False

What happens there? And why this happens?

Answer: When I asked question I treated not as a function, but actually not isn't a function. That's why not(#something) doesn't change operator precedence. For example:

not(type(1.01)) == type(1)

is the same as:

not(type(1.01) == type(1))

and:

not type(1.01) == type(1)

but not the same as:

(not type(1.01)) == type(1)
like image 958
kharandziuk Avatar asked Nov 13 '13 11:11

kharandziuk


2 Answers

Python is parsing

not(type(1.01)) == type(1)

as

not ((type(1.01)) == type(1))

(Note carefully the parentheses.)

The operator precedence table shows not has less precedence than ==. So the == operator is causing type(1.01) == type(1) to be evaluated before the not is applied.


Here is another way to see how the expression is evaluated:

In [16]: type(1.01)
Out[16]: float

In [17]: type(1)
Out[17]: int

In [18]: float == int
Out[18]: False

In [19]: not float == int   # This is same as `not (float == int)`
Out[19]: True

In [20]: not (float) == int    
Out[20]: True

In [21]: not (type(1.01)) == int
Out[21]: True

In [22]: not (type(1.01)) == type(1)
Out[22]: True
like image 165
unutbu Avatar answered Sep 26 '22 17:09

unutbu


actully you considered not as a built-in functions and use not(..) as calling a function. Infact for python not is a built-in Types. so add () would not change the result. these are some reference from python doc 2.7.5 and 3.2:

http://docs.python.org/2/library/stdtypes.html http://docs.python.org/release/2.5.2/lib/boolean.html

they both say: not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error. which as exactly the answer of your question.

like image 38
Luyi Tian Avatar answered Sep 26 '22 17:09

Luyi Tian