Python3賦值運算符實例
假設變量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