This what I got while fiddling with the python interpreter
[mohamed@localhost ~]$ python
Python 2.7.5 (default, Apr 10 2015, 08:09:14)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'a' in 'abc'
True
>>> 'a' in 'abc' == True
False
>>> 'a' in 'abc' == False
False
>>> ('a' in 'abc') == True
True
>>> ('a' in 'abc') == False
False
>>> ('a' in 'abc' == True) or ('a' in 'abc' == False)
False
>>> (('a' in 'abc') == True) or (('a' in 'abc') == False)
True
My question is why using parenthesis gives me the intended, and more logically sound, output?
Because of operator chaining, in
and ==
do not behave well together.
'a' in 'abc' == True
Transforms to -
'a' in 'abc' and 'abc' == True
Reference from documentation -
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z , except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
The similar thing happens for in
and ==
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With