Python賦值運算子範例

2019-10-16 23:08:04

假設變數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