Python3-assignment-operators-example

提供:Dev Guides
移動先:案内検索

Python 3-代入演算子の例

変数 a が値10を保持し、変数 b が値20を保持すると仮定します-

Operator Description Example
= Assigns values from right side operands to left side operand c = a PLUS b assigns value of a PLUS b into c
PLUS= Add AND It adds right operand to the left operand and assign the result to left operand c PLUS= a is equivalent to c = c PLUS a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to left operand c/= a is equivalent to c = c/ac/= a is equivalent to c = c/a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c = a is equivalent to c = c a
//= Floor Division It performs floor division on operators and assign value to the left operand c//= a is equivalent to 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