1

I found a particular bug in a piece of a function of mine, where the order of the args for the bitwise comparison OR seems to matter:

In: None or False
Out: False

In: False or None
Out: None

Checked this using Python 2.7.2 and IPython 0.10.2.

I can ensure that, in case of one element being None, making sure he's the first arg of the comparison, like this

if a==None:
    a or b
else:
    b or a

But could anyone please explain me why changing the order in an OR comparison would affect the output? Is this particular to Python?

Thanks.

pcarvalho
  • 685
  • 1
  • 5
  • 7
  • 1
    It`s the shortcut behaviour of the boolean operator `or`. If the first operand is evaluated to `false` the second will be returned. – halex Oct 03 '12 at 13:38
  • 2
    `or` is neither a bitwise operator nor a comparison operator. –  Oct 03 '12 at 13:39

3 Answers3

8

From typing help("or"):

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

In None or False, None isn't true, so False is returned.

In False or None, False isn't true, so None is returned.

Makoto
  • 104,088
  • 27
  • 192
  • 230
DSM
  • 342,061
  • 65
  • 592
  • 494
1

DSM has explained what the or operator does. Are you expecting the result to be a boolean, so that None or False or False or None is always False? If so, then you need to be explicit about it and use either bool(None or False), or if you had a lot of them to check, then any([None, False]) etc...

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

I have never seen a language where the order of the logical operator or does not matter, unless you have seen a langage where that is the case, the behaviour of python is normal.

or processes statements from left-to-right until one of them is True(or it gets to the end).

and processes statements from left-to-right until one of them is False (or it gets to the end).

The bitwise or operator (in Python, as in most languages) is a pipe '|'.

cdarke
  • 42,728
  • 8
  • 80
  • 84