Python: Assignment Operators

Assignment Operators is used to assign values to the variable.

OperatorDescriptionSyntax
Equal (=)It assign value of right side of expression to left side operand.a = b + c
Add AND(+=)It add right side operand with left side operand and then assign to left operand.

a += b

a = a + b

Subtract AND(-=)It subtracts right operand from the left operand and assign the result to left operand.

a -= b

a = a - b

Multiply AND(*=)It multiplies right operand with the left operand and assign the result to left operand.

a *= b      

a = a * b

 Divide AND(/=)It divides left operand with the right operand and assign the result to left operand.

a /= b        

a = a / b

Modulus AND(%=)It takes modulus using two operands and assign the result to left operand.

a %= b  

a = a % b

Exponent AND(**=)It performs exponential on operators and assign value to the left operand.

a **= b    

a = a ** b

Floor Division(//=)It performs floor division on operators and assign value to the left operand.

a //= b      

a = a // b

Bitwise AND(&=)It performs Bitwise and on operands and assign value to left operand.

a &= b        

a = a & b

Bitwise xOR(^=)It performs Bitwise xOR on operands and assign value to left operand.

a ^= b      

a = a ^ b

Bitwise OR(|=)It performs Bitwise OR on operands and assign value to left operand.

a |= b        

a = a | b

Bitwise Right Shift (>>=)It performs Bitwise right shift on operands and assign value to left operand.

a >>= b  .

 a = a >> b

Bitwise Left Shift(<<=)It performs Bitwise left shift on operands and assign value to left operand.

a <<= b

a= a << b

Example:

a = 4
b = 3

d = e = f = 0
g = h = i = j = 2
k = l = m = n = o = 3

c = a + b
print("c = ",c)

d += a
print("d = ",d)

e -= b
print("e = ",d)

f *= a
print("f = ",f)

g /= b
print("g = ",g)

h %= b 
print("h = ",h)

i **= a
print("i = ",i)

j //= a 
print("j = ",j)

k &= b
print("k = ",k)

l ^= b 
print("l = ",l)

m |= b
print("m = ",m)

n >>= b
print("n = ",n)

o <<= a
print("o = ",o)

Output:

c =  7
d =  4
e =  4
f =  0
g =  0.6666666666666666
h =  2
i =  16
j =  0
k =  3
l =  0
m =  3
n =  0
o =  48
Tags