Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unsupported operand type(s) for |: 'tuple' and 'bool'

Tags:

python

boolean

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'
like image 505
Or Halimi Avatar asked Mar 21 '26 21:03

Or Halimi


1 Answers

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.

like image 167
thefourtheye Avatar answered Mar 23 '26 11:03

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!