Python 赋值运算符用于对变量赋值。

以下列出Python中所有的赋值运算符和operator模块的关系。

赋值运算符operator方法说明
=没有对应的operator方法赋值
+=operator.iadd(a,b)加法赋值
-=operator.isub(a,b)减法赋值
*=operator.imul(a)乘法赋值
/=operator.itruediv(a,b)除法赋值
//=operator.ifloordiv(a,b)整除赋值,等价于结果向下取整
%=
operator.imod(a, b)取模赋值,取余数
&=operator.iand(a,b)按位与赋值
|=
operator.ior(a,b)按位或赋值
^=operator.xior(a,b)按位异或赋值
>>=
operator.irshift(a,b)右移赋值
<<=operator.ilshift(a,b)左移赋值

以上,除了=符号,其它都是运算符的简写形式,下面介绍这些运算符的例子。

赋值运算符加减乘除的例子

#!/usr/bin/python
# coding=utf-8
a=3
a+=2 # 等价于 a=a+2=5
print('加法赋值运算符结果:', a)

a-=2 # 等价于 a=a=2=3
print('减法赋值运算符结果:', a)

a*=2 # 等价于 a=a*2=6
print('乘法赋值运算符结果:', a)

a/=2 # 等价于 a=a*2=3
print('除法赋值运算符结果:', a) 
程序运行结果:
加法赋值运算符结果: 5
减法赋值运算符结果: 3
乘法赋值运算符结果: 6
除法赋值运算符结果: 3.0

赋值运算符整除取模的例子

#!/usr/bin/python
# coding=utf-8
a=9
a//=2  #结果向下取整
print('整除赋值运算符结果:', a)

a=9
a%=2 # 取余数
print('取余数赋值运算符结果:', a) 
程序运行结果:
整除赋值运算符结果: 4
取余数赋值运算符结果: 1

位运算符的例子

运算结果参考 位运算符 的计算过程。

#!/usr/bin/python
# coding=utf-8
a=9
a &= 13
print('按位与:', a)

a=9
a |= 13
print('按位或:', a)

a=9
a ^= 13
print('按位异或:', a)

a=9
a >>= 2
print('右移:', a)

a=9
a <<= 2
print('左移:', a)
程序运行结果:
按位与: 9
按位或: 13
按位异或: 4
右移: 2
左移: 36