Assignment Operators in python


Introduction

Assignment operators are used for assigning values to the variables.

In this blog, you will learn about eight different types of assignment operators used in the Python programming language. Remember that python does not support increment (++) or decrement (- -) like in other programming languages.

1. Assign (=)

Assigns values from right side operands to left side operands. It is used to assign values to variables and objects.

Example:

>>> a = 3
>>> string  = "Python"
>>> PI = 3.14
2. Add and Assign (+=)

It adds the right operand to the left operand and assigns the result to the left operand.

Example:

>>> num = 10
>>> num += 50   # Same as num = num + 50 where initial value for num is 10
>>> print(num)
60
3. Subtract and Assign (-=)

It subtracts the right operand from the left operand and assigns the result to the left operand.

Example:

>>> a = 12
>>> a -= 5   # Same as a = a - 5 where initial value for a is 12
>>> print(a)
7
4. Multiply and Assign (*=)

It multiplies the right operand with the left operand and assigns the result to the left operand.

Example:

>>> a = 12
>>> a *= 2 # Same as a = a * 2 where initial value for a is 12
>>> print(a)
24


5. Divide and Assign (/=)

It divides the left operand with the right operand and assigns the result to the left operand.

Example:

>>> a = 10
>>> a /= 5  # Same as a = a / 5 where initial value for a is 10
>>> print(a)
2.0
6. Modulus and Assign (%=)

It takes modulus using two operands and assigns the result to the left operand.

Example:

>>> num = 10
>>> num %= 3 # # Same as a = a % 3 where initial value for a is 10
>>> print(num)
1
7. Exponents and Assign (**=)

Performs exponential (power) calculation and assigns value to the left operand.

Example:

>>> a = 4
>>> a **= 2 # Same as a = a ** 2 where initial value for a is 4
>>> print(a)
16
8. Floor divide and Assign (//=)

It performs floor division on the operand and assigns value to the left operand.

Example:

>>> a = 4
>>> a //= 2 # Same as a = a // 2 where initial value for a is 4
>>> print(a)
2
Summary

We learned about eight types of assignment operators. But there are also other types of assignment operators such as &=, |=, ^=, >>=, and <<=. You can explore further it. I did not discuss them here because I haven’t seen them using frequently.

Other operators used are: