Python賦值運算符示例
下表列出了所有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