Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "and=" operator for boolean?

There is the "+=" operator for, namely, int.

a = 5
a += 1
b = a == 6 # b is True

Is there a "and=" operator for bool?

a = True
a and= 5 > 6 # a is False
a and= 5 > 4 # a is still False

I know, this 'and=' operator would correspond to:

a = True
a = a and 5 > 6 # a is False
a = a and 5 > 4 # a is still False

But, I do this operation very often and I don’t think it looks very neat.

Thanks

like image 202
nicolas.leblanc Avatar asked Dec 03 '22 22:12

nicolas.leblanc


2 Answers

Yes - you can use &=.

a = True
a &= False  # a is now False
a &= True   # a is still False

You can similarly use |= for "or=".

It should be noted (as in the comments below) that this is actually a bitwise operation; it will have the expected behavior only if a starts out as a Boolean, and the operations are only carried out with Booleans.

like image 141
Nick Peterson Avatar answered Dec 09 '22 16:12

Nick Peterson


nrpeterson showed you how to use &= with boolean.

I show only what can happend if you mix boolean and integer

a = True
a &= 0 # a is 0
if a == False : print "hello" # "hello"

a = True
a &= 1 # a is 1
if a == False : print "hello" # nothing

a = True
a &= 2 # a is 0 (again)
if a == False : print "hello" # "hello"

a = True
a &= 3 # a is 1
if a == False : print "hello" # nothing
like image 35
furas Avatar answered Dec 09 '22 15:12

furas