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

2024-03-14,,

这算是一篇《避坑文章》

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

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

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

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

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

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

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

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


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

Operator Description
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean 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~x Positive, negative, bitwise NOT
** Exponentiation [6]
await x Await expression
x[index]x[index:index]x(arguments...)x.attribute Subscription, 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个运算,前面那个表格在列在同一等级,这明显与常理不符,所以我才去查了官方资料。

《python运算符的优先级原来是这样的.doc》

下载本文的Word格式文档,以方便收藏与打印。