Karan
Karan

Reputation: 15094

Or statements problem in python

Or statements in python do not seem to work as in other languages since:

-1 < 0 | 0<0

returns False (should return true since -1<0 is True)

What is the problem?

Upvotes: 1

Views: 1208

Answers (2)

moinudin
moinudin

Reputation: 138317

| has precedence over < (see the Python operator precedence table). Use parenthesis to force the desired order of operation:

>>> -1 < 0 | 0 < 0
False
>>> -1 < (0 | 0) < 0
False
>>> (-1 < 0) | (0 < 0)
True

You might prefer to use the boolean or operator (equivalent to || in many other languages) instead of the bitwise |, which will give you the desired precedence without parenthesis:

>>> -1 < 0 or 0 < 0
True

As a side note, -1 < 0 < 0 (or a < b < c) does the intuitive thing in Python. It is equivalent to a < b and b < c. Most other languages will evaluate it as (a < b) < c, which is not typically what you'd expect.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375484

There are two problems: First, the precedence of the operators is not what you expect. You can always add parens to make it explicit:

>>> (-1 < 0) | (0 < 0)
True

Also, single-pipe is a logical or that evaluates both of its arguments all the time. The equivalent of other languages's pipe-pipe is or:

>>> -1 < 0 or 0 < 0
True

Upvotes: 9

Related Questions