假设变量a
的值10
,变量b
的值是21
,则 -
运算符 | 描述 | 示例 |
---|---|---|
= |
将右侧操作数的值分配给左侧操作数 | c = a + b 表示将a + b 的值分配给c |
+= |
将右操作数相加到左操作数,并将结果分配给左操作数 | c + = a 等价于c = c + a |
-= |
从左操作数中减去右操作数,并将结果分配给左操作数 | c -= a 等价于 c = c - a |
*= |
将右操作数与左操作数相乘,并将结果分配给左操作数 | c *= a 等价于 c = c * a |
/= |
将左操作数除以右操作数,并将结果分配给左操作数 | c /= a 等价于 c = c / a |
%= |
将左操作数除以右操作数的模数,并将结果分配给左操作数 | c %= a 等价于 c = c % a |
**= |
执行指数(幂)计算,并将值分配给左操作数 | c **= a 等价于 c = c ** a |
//= |
运算符执行地板除运算,并将值分配给左操作数 | c //= a 等价于 c = c // a |
实例
假设变量a
的值是10
,变量b
的值是21
,参考以下代码实现 -
#!/usr/bin/python3
#coding=utf-8
#save file : assignment_operators_example.py
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c += a
print ("Line 2 - Value of c is ", c )
c *= a
print ("Line 3 - Value of c is ", c )
c /= a
print ("Line 4 - Value of c is ", c )
c = 2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
将上面代码保存到文件: comparison_operators_example.py 中,执行结果如下 -
F:\worksp\python>python assignment_operators_example.py
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864