发布于 2015-06-21 10:32:26 | 162 次阅读 | 评论: 0 | 来源: 网络整理
下表列出了所有Python语言支持的赋值运算符。假设变量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 |
试试下面的例子就明白了所有在Python编程语言可供选择的赋值运算符:
#!/usr/bin/python
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
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864