温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python运算符的优先级原来是这样的

发布时间:2020-07-25 07:29:39 来源:网络 阅读:1876 作者:xceliuzy 栏目:编程语言

这算是一篇《避坑文章》

为什么叫避坑呢,起因是自己掉过很多人挖的坑,比如国内转来转去的东西,大多是你抄我我抄你,从最起头就有问题,抄下去问题或许更多;有些又是因为翻译的问题,或是因为翻译造成的理解问题;有些是细节问题,一点点不起眼的地方,就引起最终的错误;有些是版本更新的问题。

所以想来想去,有时间的时候就写写,希望有人能看到,避免走一些弯路,我的目的就达到了。

(自己挖的坑暂时就不提了。。。)


最近想折腾一下python,就从头开始看了看,因为这样一道问题:

if not 1 + 1 == y or x == 4 and 7 == 8:

当然涉及到了pythone运算符的优先级,有点不清楚python的运算优先级,就去查了一下。

结果发现,好几个地方的内容是这样的,我粘了一份过来(从高到低):

运算符描述
**指数 (最高优先级)
~ + -按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
* / % //乘,除,取模和取整除
+ -加法减法
>> <<右移,左移运算符
&位 'AND'
^ |位运算符
<= < > >=比较运算符
<> == !=等于运算符
= %= /= //= -= += *= **=赋值运算符
is is not身份运算符
in not in成员运算符
not and or逻辑运算符


实际上,官方是这样的(从低到高):

OperatorDescription
lambdaLambda expression
if – elseConditional expression
orBoolean OR
andBoolean AND
not xBoolean NOT
innot inisis not<<=>>=!===Comparisons, including membership tests and identity tests
|Bitwise OR
^Bitwise XOR
&Bitwise AND
<<>>Shifts
+-Addition and subtraction
*@///%Multiplication, matrix multiplication, division, floor division, remainder [5]
+x-x~xPositive, negative, bitwise NOT
**Exponentiation [6]
await xAwait expression
x[index]x[index:index]x(arguments...)x.attributeSubscription, slicing, call, attribute reference
(expressions...)[expressions...]{key: value...},{expressions...}Binding or tuple display, list display, dictionary display, set display

来源:

https://docs.python.org/3/reference/expressions.html#operator-precedence


各位看官发现区别没有?

我第一时间发现的问题就是,与或非这3个运算,前面那个表格在列在同一等级,这明显与常理不符,所以我才去查了官方资料。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI