Or statements in python do not seem to work as in other languages since:
-1 < 0 | 0<0
returns False (should retu开发者_高级运维rn true since -1<0 is True)
What is the problem?
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
| 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.
加载中,请稍侯......
精彩评论