I got strange error when I tried to use "|" operator in if with tuple.
#example
Myset = ((1, 3), (4, 6), (3, 1), (2, 2), (3, 5), (2, 4), (3, 3))
courd = (4,6)
if(courd[0] - 1 ,courd[1] - 1 in d ):
isSafe = True # work as expected
but if I will try something like this:
if((courd[0] - 1 ,courd[1] - 1 in d) | 2==2 ): # or something else that involved "|"
isSafe = True
I'm getting
Traceback (most recent call last):
File "<pyshell#87>", line 1, in <module>
if((courd[0] - 1 ,courd[1] - 1 in d )| (2 == 2)):
TypeError: unsupported operand type(s) for |: 'tuple' and 'bool'
You need to use parens, as needed, like this
if((courd[0] - 1, courd[1] - 1) in d):
pass
Now, it will create a tuple (courd[0] - 1, courd[1] - 1)
and it will check if it is in d
. In the next case,
if((courd[0] - 1, courd[1] - 1 in d) | 2 == 2):
pass
(courd[0] - 1, courd[1] - 1 in d)
will be evaluated first and that will create a tuple. And then 2 == 2
will be evaluated (since |
has lower precedence than ==
) to True
, which is basically a boolean. So, you are effectively doing
tuple | boolean
That is why you are getting that error.
Note: |
is called bitwise OR in Python. If you meant logical OR
, you need to write it like this
if(((courd[0] - 1, courd[1] - 1) in d) or (2 == 2)):
pass
Now, (courd[0] - 1, courd[1] - 1)
will be evaluated first to create a tuple and then the tuple will be checked if it exists in d
(this will return either True
or False
, a boolean) and then (2 == 2)
will be evaluated which returns True
. Now logical or
would happily work with two booleans.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments