logo

Python Assignment Operators Example


Show

Assume variable a holds 10 and variable b holds 20, then:

OperatorDescriptionExample
=Assigns values from right side operands to left side operandc = a + b assigns value of a + b into c
+= Add ANDIt adds the right operand to the left operand and assigns the result to the left operandc += a is equivalent to c = c + a
-= Subtract ANDIt subtracts the right operand from the left operand and assigns the result to the left operandc -= a is equivalent to c = c - a
*= Multiply ANDIt multiplies the right operand with the left operand and assigns the result to the left operandc *= a is equivalent to c = c * a
/= Divide ANDIt divides the left operand with the right operand and assigns the result to the left operandc /= a is equivalent to c = c / a
%= Modulus ANDIt takes modulus using two operands and assigns the result to the left operandc %= a is equivalent to c = c % a
**= Exponent ANDPerforms exponential (power) calculation on operators and assign value to the left operandc **= a is equivalent to c = c ** a
//= Floor DivisionIt performs floor division on operators and assigns value to the left operandc //= a is equivalent to c = c // a

Example

Assume variable a holds 10 and variable b holds 20, then:

#!/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 the 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

Here at Intellinuts, we have created a complete Python tutorial for Beginners to get started in Python.