How we evaluate '|' operator? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How we evaluate '|' operator?

a=5|5 b=10|5 print(a+b) # output is 20

31st Jul 2020, 8:49 AM
Mohini Yadav
Mohini Yadav - avatar
3 Answers
31st Jul 2020, 8:58 AM
Simba
Simba - avatar
+ 6
you'll get your answer here... https://www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-bitwise-operators/ a = 5|5 5 = 0101(Binary) 0101 (5 in Decimal) OR 0101 (5 in Decimal) - - - - - 0101 (which is 5 in Decimal) so [a = 5] b = 10|5 5 = 0101(Binary) 10=1010(Binary) 1010 (10 in Decimal) OR 0101 (5 in Decimal) - - - - - 1111 (which is 15 in Decimal) so [b = 15] Now, print(a+b) => print(5+15) => 20 _____________-_________--_________-______________- Bonus: why is 0101 equal to 5? So the trick is simple just check for 1s in the binary number and then add the corresponding vertical/column value to get the Decimal value. for example: [8][4][2][1] 0 1 0 1 here: we have 1 at [4] and [1] so we just add them to get the Decimal value of ([4]+[1]=5). Similarly for 1111: [8][4][2][1] 1 1 1 1 here: we have all 1s at [8], [4], [2] and [1] so we just add them to get the Decimal value of ([8]+[4]+[2]+[1]=15).
31st Jul 2020, 8:54 AM
Rohit
+ 6
It is bitwise OR operators. It evaluates true only if one bit is true. In case of integers it will do the same for their binary representation. 5|5 = 5 10 = 1010 ( in binary ) 5 = 101 (in binary) 10 | 5 is same as 1010 Or 0101 -------------- = 1111 Which is 20 in binary.
31st Jul 2020, 8:57 AM
Arsenic
Arsenic - avatar