Python赋值运算符
假设变量a持有10,变量b持有20,则-
1
值从右侧操作数分配给左侧操作数
c=a+bassignsvalueofa+bintoc
将右操作数添加到左操作数,并将结果分配给左操作数
c+=aisequivalenttoc=c+a
如果两个操作数的值不相等,则条件为true。它将从左侧操作数中减去右侧操作数并将结果分配给左侧操作数
c-=aisequivalenttoc=c-a
将右操作数与左操作数相乘并将结果分配给左操作数
c*=aisequivalenttoc=c*a
将左操作数除以右操作数,并将结果分配给左操作数
c/=aisequivalenttoc=c/a
使用两个操作数取模并将结果分配给左操作数
c%=aisequivalenttoc=c%a
对运算符执行指数(幂)计算并将值分配给左操作数
c**=aisequivalenttoc=c**a
它对运算符执行地板除法并将值赋给左操作数
示例
假设变量a持有10,变量b持有20,则-
#!/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