Reputation: 2046
print('a' in 'aa')
print('a' in 'aa' == True)
print(('a' in 'aa') == True)
print('a' in ('aa' == True))
The output is
True
False
True
Traceback (most recent call last):
File "main.py", line 6, in <module>
print('a' in ('aa' == True))
TypeError: argument of type 'bool' is not iterable
If line 2 is neither line 3 nor line 4, then what is it? How does it get False?
Upvotes: 5
Views: 500
Reputation: 51633
According to Expressions
print('a' in 'aa' == True)
is evaluated as
'a' in 'aa' and 'aa' == True
which is False
.
See
print("a" in "aa" and "aa" == True)
==> False
The rest is trivial - it helps to keep operator precedence in mind to figure them out.
Similar ones:
with different statements. I flagged for dupe but the UI is wonky - I answered non the less to explain why yours exactly printed what it did.
Upvotes: 9
Reputation: 1695
Case 1 : it's simple the answers is True
.
print('a' in 'aa')
Case 2 : This operation is evaluated as 'a' in 'aa' and 'aa' == True
, so obviously it will return false.
print('a' in 'aa' == True)
Case 3: Now because we have ()
enclosing ('a' in 'aa')
and the precedence of ()
is highest among all so first 'a' in 'aa'
is evaluated as True
and then True == True
print(('a' in 'aa') == True)
Case 4 : Same as above because of precedence of ()
, its evaluated as 'aa' == True
, which will result in error as it tries to apply in
on a non iterable that is bool value.
print('a' in ('aa' == True))
Upvotes: 1