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
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.
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
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