Python in operator priority and comparison

The following comparisons are made True:

>>> '1' in '11'
True
>>> ('1' in '11') == True
True

And using parentheses in another way, I get a TypeError:

>>> '1' in ('11' == True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

So how do I get Falsewithout parentheses?

>>> '1' in '11' == True
False
+5
source share
4 answers

The Python manual states that inthey ==have the same priority:

http://docs.python.org/reference/expressions.html#summary

Thus, they are evaluated from left to right by default, but also a chain to consider. The expression above ( '1' in '11' == True) is actually evaluated as ...

('1' in '11') and ('11' == True)

which of course False. If you don't know what a chain is, this is what allows you to do something like ...

if 0 < a < 1:

Python, , ( "a 0, 1" ).

+11

. Python . :

'1' in '11' == True

:

('1' in '11') and ('11' == True)

, True 1 1 "11".

+4

x < y < z x < y and y < z. :

>>> (False == True) == False
True
>>> False == (True == False)
True
>>> False == True == False
False
>>>

, '1' in '11' == True ('1' in '11') and ('11' == True)

+2
source

What is going on here?

'1' in '11' == True  ==>  False

- the same as:

'1' in ('11' == True)

but

('11' == True) ==> False

and

'1' in False

not determined.

-1
source

All Articles