-1

when I do the following in python shell !

>> print 2 | 4
>> 6

why pipe symbol in python adds to integer ?

Ciasto piekarz
  • 7,175
  • 13
  • 72
  • 173
  • 1
    Because it's not a pipe : https://docs.python.org/2/library/stdtypes.html#bitwise-operations-on-integer-types –  Nov 02 '15 at 05:10

3 Answers3

6

It is not a pipe symbol, it is a bitwise OR.

2 in binary:    10
4 in binary:   100
__________________
with or:       110  (1 or 0: 1, 1 or 0: 1, 0 or 0: 0)

And 110 in binary is 6 decimal.

daniel451
  • 9,975
  • 16
  • 60
  • 124
2

It's not addition. It's a bitwise OR. 2 and 4 just happen to be 010 and 100 in binary, so both their sum and their OR is 110 (6).

More info and examples at https://wiki.python.org/moin/BitwiseOperators

viraptor
  • 32,414
  • 8
  • 104
  • 182
1

The pipe symbol stands for bitwise OR in python. Since bin(2) == '0b10', bin(4) == '0b100' and bin(6) = '0b110', you can see that 2 | 4 actually did a bitwise OR.

darkryder
  • 762
  • 1
  • 8
  • 23