Python Assignment Operators +=, *=, -=, /=
<Arithmetic Operators Comparison Operators >
Assignment operators used to assign value to the variable.
Operators | Meaning | Example |
---|---|---|
(=) Equal | An equal sign is used to assign value to the variable. | >>>x=1 >>>y=2+1 >>>a=b=c=d=10 >>>c=x+y |
(+= ) Add and | Add the value of the left and right operands and then save the result to the left operand | >>>a=10 >>>b=20 >>>b+=a # equivalent to b=b+a >>>print(b) >>>30 |
( -= ) Subtract and | Subtract the value of the right operand from the left and then save the result to the left operand. | >>>a=10 >>>b=20 >>>b-=a # equivalent to b=b-a >>>print(b) >>>10 |
( *= ) Multiply and | Perform the multiplication of the left and right operands and then store the result in the left operand. | >>>a=3 >>>b=5 >>>b*=a # equivalent to b=b*a >>>print(b) >>>15 |
(/=) Division and | First divides the value of the left operand with the right operand and then save the result to the left operand | >>>a=10
>>>b=20 >>>b/=a # equivalent to b=b/a >>>print(b) >>>2 |
(%=) Modulus and | Divides the left operand with the right operand and then save the result to the left operand. | >>>a=10 >>>b=22 >>>b%=a # equivalent to b=b%a >>>print(b) >>>2 |
(//=) Floor division and | Perform the floor division on the left operand with the right operand and then save the result to the left operand. | >>>a=10 >>>b=22 >>>b//=a # equivalent to b=b//a >>>print(b) >>>2 |
(**=) Exponent and | Perform the exponential operation on the left operand and then save the result to the left operand. | >>>a=2 >>>a**=2 # equivalent to a=a**2 >>>print(a) >>>4 |
Example Program with Assignment Operators
>> # assign value to the variables
>> a=30
>> b=20
>> c=d=7
>> # shows how to use (+=) operator
>> b+=a # equivalent to b=b+a
>> print(b)
50
>> # shows how to use (-=) operator
>> a-=c # equivalent to a=a-c
>> print(a)
23
>> # shows how to use (*=) operator
>> a*=2 # equivalent to a=a*2
>> print(a)
46
>> # shows how to use (/=) operator
>> a/=d # equivalent to a=a/d (a=46/7)
>> print(a)
6.571428571428571
>> # shows how to use (//=) operator
>> a//=2 # equivalent to a=a//2 (a=6.571//2)
>> print(a)
3.0
>> # shows how to use (%=) operator
>> d%=2 # equivalent to d=d%2 (d=7%2)
>> print(d)
1
>> # shows how to use (**=) operator
>> c**=2 # equivalent to c=c**2
>> print(c)
49
<Arithmetic Operators Comparison Operators >