Assignment operators are used to assigning the value of an expression to a variable. The usual assignment operator is ‘=’.

In addition, Python has a set of ‘Shortcut’ assignment operators, which are used in the form v op=exp. Where v is a variable, exp is an expression, and op is the Python operator. Here op= is known as a Shortcut assignment operator.

Here v op=exp is equivalent to v=v op (exp). Consider an example a+=10. Here this statement is the same as a=a+10.

Python supports the following shortcut assignment operators:

+=, -=, *=, /=, %=, //=, **=

## Python Assignment Operator Examples

Now we are giving examples of the following assignment operations.

Add and assign using += operator:

Here += operator adds the operands on the left and right side of the operator and assigns the result to the operand on the left.

For example, a+=c is same as a=a+c.

#### Example 1:

a=90 c=80 a+=c print(a)

##### Output:

170

#### Example 2:

#An example of the += operator on strings

x="wel" y="come" x+=y print(x)

##### Output:

welcome

#### Example 3:

Subtract and assign using -= Shortcut assignment operator:

This subtracts operands on the right from the operand on the left of the operator and assigns the result to the operand on the left.

For example, a-=c is the same as a=a-c.

a=70 c=60 a-=c print(a)

##### Output:

10

#### Example 4:

Multiply and assign using *= operator:

This multiplies the operands and assigns the result to the operand on the left side of the operator.

For example, x*=y is the same as x=x*y

x=4 y=3 x*=y print(x)

##### Output:

12

#### Example 5:

Divide and assign:

In this operation, the /= operator divides the operand on the left side of the operator with the operand on its right. Actually, the division operator returns the quotient. Then the result is assigned to the operand to the left of the division operator.

For example, m/=n is the same as m=m/n

m=90 n=10 m/=n print(m)

##### Output:

9

#### Example 6:

Modulus and assign operation:

This divides the operand on the left side of the operator with the operand on its right. The modulus operator returns the remainder. Then the remainder is assigned to the operand to the left of the operator.

For example, a%=b is the same as a=a%b.

a=90 b=60 a%=b print(a)

##### Output:

30

#### Example 7:

Floor division:

In this operation, the //= operator divides the operands and returns the quotient. Then the quotient is assigned to the operand on the left of the operator.

For example, a//=b is same as a=a//b.

a=9 b=3 a//=b print(a)

##### Output:

3

#### Example 8:

Exponent and assign:

This performs an exponential calculation, that is, raises the operand on the right side to the operand on the left of the operator and assign the result in the left operand.

For example, g**=h is the same as g=g**h.

g=4 h=3 g**=h print(g)

##### Output:

64

## Leave a comment