Boolean operators vs Bitwise operators

Jiew Meng picture Jiew Meng · Oct 2, 2010 · Viewed 42.3k times · Source

I am confused as to when I should use Boolean vs bitwise operators

  • and vs &
  • or vs |

Could someone enlighten me as to when do i use each and when will using one over the other affect my results?

Answer

Mark Byers picture Mark Byers · Oct 2, 2010

Here are a couple of guidelines:

  • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.
  • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.

The short-circuiting behaviour is useful in expressions like this:

if x is not None and x.foo == 42:
    # ...

This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.