假设变量a=10和变量b=20,那么
运算符 | 描述 | 示例 |
---|---|---|
= |
将操作符的右侧操作数赋值给左侧的操作数
|
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 |
//= |
这对操作符两侧的操作数进行地板除并赋值给左操作数
|
c //= a 相当于 c = c // a |
实例
假设变量 a = 10,变量b = 20,那么 -
#!/usr/bin/python3 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)
当你执行上面的程序,它会产生以下结果 -
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