Assignment operators are used to assign a value to a variable. The most basic assignment operator in Python is the =
sign, which assigns the value on the right side of the operator to the variable on the left side.
Types of Assignment Operators
=
(Simple Assignment)+=
(Add and Assignment)-=
(Subtract and Assignment)*=
(Multiply and Assignment)/=
(Divide and Assignment)%=
(Modulus and Assignment)**=
(Exponent and Assignment)//=
(Floor Division and Assignment)
Simple Assignment (=)
Python
x = 5
Add and Assignment (+=)
Python
x = 5
x += 3 # x = x + 3
print(x) # Output: 8
Subtract and Assignment (-=)
Python
x = 5
x -= 3 # x = x - 3
print(x) # Output: 2
Multiply and Assignment (*=)
Python
x = 5
x *= 3 # x = x * 3
print(x) # Output: 15
Divide and Assignment (/=)
Python
x = 5
x /= 3 # x = x / 3
print(x) # Output: 1.6666666666666667
Modulus and Assignment (%=)
Python
x = 5
x %= 3 # x = x % 3
print(x) # Output: 2
Exponent and Assignment (**=)
Python
x = 5
x **= 3 # x = x ** 3
print(x) # Output: 125
Floor Division and Assignment (//=)
Python
x = 5
x //= 3 # x = x // 3
print(x) # Output: 1
It is important to note that these operators work on the variable on the left side of the operator, and the value on the right side is assigned to it. These operators are a shorthand way of performing the corresponding operation and assignment in one step.