I’m learning Python assignment operators. Why is the result of the operation below equal to 2? Please give me detail.
print(2 & 3)
I’m learning Python assignment operators. Why is the result of the operation below equal to 2? Please give me detail.
print(2 & 3)
&
is not an assignment operator, but a bitwise AND operator. It returns a number of all the bits that its two operands have set in common.
0b10 => 2
0b11 => 3
^
\
common bit
The common bit is in the two’s placeholder.
0b1000 => 8
0b0111 => 7
Note that 7 & 8
=> 0
since they have no bits in common.
0b1010 => 10
& 0b1111 => 15
_ 0b1010
10 & 15 => 10
0b1111 => 15
& 0b0111 => 7
_ 0b0111
15 & 7 => 7
Note that ANDing two binary numbers will never give a result greater than the smaller of the two numbers.
Side note. Bitwise ANDing any number with 1
will tell us if the number is odd.
22 & 1 => 0
23 & 1 => 1