dhana
dhana

Reputation: 6525

How to use bitwise operators in Python?

I am new to python. I have tested my interpreter using following code,

In [1]: 2 and 3
Out[1]: 3

In [2]: 3 and 2
Out[2]: 2

In [3]: 3 or 2
Out[3]: 3

In [4]: 2 or 3
Out[4]: 2

In the above, take 2=0010 and 3=0011. the result is,

+ 0010
  0011
  ----
  0010=2

But Out[1] gave the 3(not exact) and out[2] gave the 2(exact).

What is the difference in two cases?

Upvotes: 0

Views: 541

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1125018

You are using boolean logic or and and, which short-circuit (return the first operand for which the outcome of the operator is fixed).

You are looking for the binary bitwise operators instead, | and &:

>>> 0b10 & 0b1
0
>>> 0b10 | 0b1
3

The or operator returns the first operand if it is true-y (not empty or numeric 0), the second operand otherwise, the and operator returns the first if it is false-y, the second operator otherwise. This is why you see 3 and 2 return 2, and 3 or 2 return 3. Both 2 and 3 are non-zero, so true in a boolean context.

Using 0 as a false value you'd see:

>>> 3 and 0
0
>>> 3 or 0
3
>>> 0 and 3
0
>>> 0 or 3
3

Upvotes: 10

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

use &, and is boolean AND in python:

>>> 2 & 3
2
>>> 3 & 2
2

Upvotes: 1

Sukrit Kalra
Sukrit Kalra

Reputation: 34531

You are looking for the bitwise and, &.

and and or are boolean operators in Python, whereas & and | are bitwise operators.

Example -

>>> 2 and 3
3
>>> 2 & 3
2

Upvotes: 2

user2492738
user2492738

Reputation: 83

You are looking for the bitwise operators,

>>> 2 & 3
2
>>> 2 | 3
3

By just doing 2 and 3 you are evaluating 2, which is True, then 3 (also True) and Python returns that second number. So you get 3.

With 2 or 3, it short-circuits and just returns 2 since 2 is True.

Upvotes: 6

Related Questions