I found this strange if
-statement in somebody else’s code:
if variable & 1 == 0:
I don\'t understand it. It should have two
Your only concern is probably the operator &
. It is a bitwise and which takes the binary format of the two operands and perform "logic and" on each pair of bits.
For your example, consider the following:
variable = 2 #0b0010
if variable & 1 == 0:
print "condition satisfied" # satisfied, 0b0010 & 0b0001 = 0
variable = 5 #0b0101
if variable & 1 == 0:
print "condition satisfied" # not satisfied, 0b0101 & 0b0001 = 1
Note:
variable = 6 #0b0110
if variable & 2 == 0:
print "condition satisfied" # not satisfied, 0b0110 & 0b0010 = 2 (0b0010)