-1

when I do the following in python shell !

>> print 2 | 4
>> 6

why pipe symbol in python adds to integer ?

Ciasto piekarz
  • 7,853
  • 18
  • 101
  • 197
  • 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

7

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
  • 10,626
  • 19
  • 67
  • 125
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
  • 33,322
  • 10
  • 107
  • 191
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
  • 792
  • 1
  • 8
  • 25