Python Compound Assignment Operators
Python Compound Assignment Operators
Python compound assignment operators support shorthand notation to avoid the repetition of the left-hand side variable on the right-hand side. A compound operator uses two or more operator symbols.
Python Compound Assignment Operators
The compound assignment operators are also known as short-hand assignment operators. For example, the statement
i=i+1
It can be written in compact form as shown below:
i+=1 # This will add 1 to variable i and assign the result to the variable i.
The compound assignment operators are as follows:
Python Compound Assignment Operators |
Description |
+= |
The += operator adds the right operand to the left operand and assigns the result to the left operand. |
-= |
The -= operator subtracts the right operand from the left operand and assigns the result to the left operand. |
*= |
The *= operator multiplies the right operand with the left operand and assigns the result to the left operand. |
/= | The /= operator divides the left operand with the right operand and assigns the result to the left operand. |
//= | The //= operator performs the floor division on operands and assigns value to the left operand. |
**= | The **= operator performs the exponential calculation on operands and assigns the result value to the left operand. |
%= | The %= operator takes the modulus using the two operands and assigns the result value to the left operand. |
Example
# Python program to demo addition and assignment # Compound operator. # Python Tutorials - www.TestingDocs.com x = 10 y = 20 x += y # This expression is equivalent to x = x + y print("Value of x is", x)
—
Python Tutorials
Python Tutorial on this website can be found at:
https://www.testingdocs.com/python-tutorials/
More information on Python is available at the official website: