1

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?

2
  • What makes you call this an "or statement"? What tutorial did you see this in? Can you provide a link or a quote? Commented Dec 26, 2010 at 15:12
  • 1
    Notice that most other languages parse this identical to Python. You probably confused | with || (used e.g. in C and Java). (Other languages will evaluate the expression differently to Python though, but that is unrelated to the bitwise or operator, and instead to the way Python has special treatment for statement such as x < y < z which is missing from other languages.) Commented Dec 26, 2010 at 15:54

2 Answers 2

9

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
Sign up to request clarification or add additional context in comments.

2 Comments

My 2.6.6 Python prompt printed "True"
My bad, I typo'd and had (-1 < 0) | (0 | 0)
1

| 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.