Reputation: 113
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
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