开发者

Or statements problem in python

开发者 https://www.devze.com 2023-02-01 19:35 出处:网络
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)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号