ruler
ruler

Reputation: 623

what does the | symbol do in python

I'm wondering what | does in python. I thought it chose the greater value but it seems I was wrong because this is what I tried at first.

>>> a = 10
>>> b = 5
>>> a | b
10

Then I tried this:

>>> a = 10
>>> b = -1
>>> a | b
-1

I tried with some other negative numbers and it continued to return -1 so it's not choosing the least value either as far as I know so what is it doing?

Upvotes: 0

Views: 125

Answers (3)

Konrad Talik
Konrad Talik

Reputation: 916

Someone is making jokes here :P

| operator is a "bitwise or" operator. In your example:

10 | 5 means (in bits):

  1010
| 0101
= 1111

Which gives:

>>> a = 10
>>> b = 5
>>> a | 5
15

(in my Python2.7 :P)

Upvotes: 1

Paul Draper
Paul Draper

Reputation: 83255

It does a bitwise "or".

http://en.wikipedia.org/wiki/Bitwise_operation

It is also in C, C++, Java, Javascript, etc.

Upvotes: 6

Thane Brimhall
Thane Brimhall

Reputation: 9555

The pipe character is a bitwise or operator. Refer to the documentation.

If you want to choose the greater value, use the max builtin:

>>> max(1, 2)
2

Upvotes: 2

Related Questions