How or operator works? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How or operator works?

Can someone explain me how this works (in Python): print(5|3) Output is 7 I have understood that | is OR operator. But I haven't found logic how it works in my example above.

13th Feb 2019, 9:40 AM
Jari
Jari - avatar
2 Answers
+ 11
OR (|) is a bitwise operator in Python that works on two operands which are in the form of bits i.e. binary operators. The bitwise OR works in the following order : ---------------------------------------- | Op 1 | Op 2 | Result | ---------------------------------------- | 0 | 0 | 0 | | 0 | 1 | 1 | | 1 | 0 | 1 | | 1 | 1 | 1 | ---------------------------------------- So wherever there is 1 in a single operand the result will always be 1. Otherwise it will be 0. If we perform the operation 5|3 the result will be : 5 : 0000 0101 3 : 0000 0011 -------------------- _ : 0000 0111 As the Decimal Value Of 0000 0111 is 7. So 5|3 is 7.
13th Feb 2019, 11:12 AM
Nova
Nova - avatar
+ 8
The bit operators compare the bit patterns of the numbers. | sets the bit to 1 if at least one of the two compared bits is 1. 5 in binary is 101. 3 in binary is 011. --------------------------- So the result: 111 which equals to 7 in decimal system.
13th Feb 2019, 9:45 AM
HonFu
HonFu - avatar