Python Assignment Operators Example
Advertisements
Following table shows all the assignment operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then:
| Operator | Description | Example |
|---|---|---|
| = | Simple assignment operator, Assigns values from right side operands to left side operand | c = a + b will assigne value of a + b into c |
| += | Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand | c += a is equivalent to c = c + a |
| -= | Subtract AND assignment operator, 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 assignment operator, 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 assignment operator, It divides left operand with the right operand and assign the result to left operand | c /= a is equivalent to c = c / a |
| %= | Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand | c %= a is equivalent to c = c % a |
| **= | Exponent AND assignment operator, Performs exponential (power) calculation on operators and assign value to the left operand | c **= a is equivalent to c = c ** a |
| //= | Floor Dividion and assigns a value, Performs floor division on operators and assign value to the left operand | c //= a is equivalent to c = c // a |
Example:
Try following example to understand all the assignment operators available in Python programming language:
#!/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
When you execute the above program it produces following result:
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