On this page

Python 运算符

Python 运算符

运算符用于对变量和值执行运算。 在下面的例子中,我们使用+运算符将​​两个值相加:

例子

print(10 + 5)

Python 将运算符分为以下几组:

  • 算术运算符
  • 赋值运算符
  • 比较运算符
  • 逻辑运算符
  • 身份运算符
  • 会员运营商
  • 按位运算符

Python 算术运算符

算术运算符与数值一起使用来执行常见的数学运算:

OperatorNameExample
+Additionx + y
-Subtractionx - y
|Multiplication|x y
/Divisionx / y
%Modulusx % y
|Exponentiation|x y
//Floor divisionx // y

Python 赋值运算符

赋值运算符用于给变量赋值:

OperatorExampleSame As
=x = 5x = 5
+=x += 3x = x + 3
-=x -= 3x = x - 3
=|x = 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
//=x //= 3x = x // 3
=|x = 3x = x ** 3
&=x &= 3x = x & 3
|=x |= 3x = x | 3
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = x << 3
:=print(x := 3)x = 3
print(x)

Python 比较运算符

比较运算符用于比较两个值:

OperatorNameExample
==Equalx == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Python 逻辑运算符

逻辑运算符用于组合条件语句:

OperatorDescriptionExample
andReturns True if both statements are truex < 5 and x < 10
orReturns True if one of the statements is truex < 5 or x < 4
notReverse the result, returns False if the result is truenot(x < 5 and x < 10)

Python 身份运算符

身份运算符用于比较对象,不是比较它们是否相等,而是比较它们是否实际上是同一个对象,具有相同的内存位置:

OperatorDescriptionExample
isReturns True if both variables are the same objectx is y
is notReturns True if both variables are not the same objectx is not y

Python 成员运算符

成员运算符用于测试对象中是否存在序列:

OperatorDescriptionExample
inReturns True if a sequence with the specified value is present in the objectx in y
not inReturns True if a sequence with the specified value is not present in the objectx not in y

Python 按位运算符

按位运算符用于比较(二进制)数字:

OperatorNameDescriptionExample
&ANDSets each bit to 1 if both bits are 1x & y
|ORSets each bit to 1 if one of two bits is 1x| y
^XORSets each bit to 1 if only one of two bits is 1x ^ y
~NOTInverts all the bits~x
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall offx << 2
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall offx >> 2

运算符优先级

运算符优先级描述了运算的执行顺序。

例子

括号具有最高优先级,这意味着必须首先评估括号内的表达式:

print((6 + 3) - (6 + 3))

例子

乘法的*优先级高于加法+,因此乘法先于加法进行计算:

print(100 + 5 * 3)

优先顺序如下表所述,最高优先级从上至下:

OperatorDescription
()Parentheses
**Exponentiation
+x -x ~xUnary plus, unary minus, and bitwise NOT
* / // %Multiplication, division, floor division, and modulus
+ -Addition and subtraction
<< >>Bitwise left and right shifts
&Bitwise AND
^Bitwise XOR
\|Bitwise OR
== != > >= < <= is is not in not inComparisons, identity, and membership operators
notLogical NOT
andAND
orOR

如果两个运算符具有相同的优先级,则从左到右计算表达式。

例子

加法+和减法-具有相同的优先级,因此我们从左到右计算表达式:

print(5 + 4 - 7 + 3)