German
German

Reputation: 113

Why does (0>1 + 0>9) return False, but ((0>1) + (0>9)) return 0?

When adding boolean expressions in python, it seems that enclosing them in parentheses casts them into int when you add them, but not doing so maintains their types:

>>> ((0>1) + (0>9))
0
>>> (0>1 + 0>9)
False
>>> (0>1 + (0>9))
False

Why is this? It seems to me that parentheses should only be used to change the order of operations (except for some cases where you use parentheses to define tuples), not the type of the contents, so I would expect:

(<expression>) == <expression>

Upvotes: 2

Views: 98

Answers (1)

wim
wim

Reputation: 363456

>>> ((0>1) + (0>9)) 
0

This is integer addition, since False is an integer instance. bool doesn't define addition, so False + False is resolved on the parent class int.__add__.

>>> (0>1 + 0>9)
False

This is a chained comparison, it's 0 > 1 > 9 in disguise.

>>> (0>1 + (0>9))
False

This is a regular comparison, it's 0 > 1 + False in disguise.

Upvotes: 5

Related Questions