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?
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory.
== is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical.
Python has two operators for equality comparisons, “is” and “==” (equals).
The is operator compares the identity of two objects while the == operator compares the values of two objects. There is a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.
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.
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))
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