Python Assignment Operators
Assignment Operators in Python
Assignment operators in Python are used to assign values to variables. While the basic assignment operator is =
, there are also compound assignment operators that combine an operation with assignment, allowing for more concise code.
Basic Assignment Operator
=
: The basic assignment operator assigns the value on the right to the variable on the left.
Example of Basic Assignment
Compound Assignment Operators
These operators perform an operation on the variable and then assign the result back to that variable.
Operator | Description | Example | Equivalent to |
---|---|---|---|
+= | Adds the right operand to the left operand and assigns the result to the left operand | x += 5 | x = x + 5 |
-= | Subtracts the right operand from the left operand and assigns the result to the left operand | x -= 3 | x = x - 3 |
*= | Multiplies the left operand by the right operand and assigns the result to the left operand | x *= 2 | x = x * 2 |
/= | Divides the left operand by the right operand and assigns the result to the left operand | x /= 4 | x = x / 4 |
%= | Performs modulus operation and assigns the result to the left operand | x %= 3 | x = x % 3 |
**= | Raises the left operand to the power of the right operand and assigns the result to the left operand | x **= 2 | x = x ** 2 |
//= | Performs floor division and assigns the result to the left operand | x //= 3 | x = x // 3 |
Examples of Compound Assignment Operators
1. Addition Assignment (+=
)
2. Subtraction Assignment (-=
)
3. Multiplication Assignment (*=
)
4. Division Assignment (/=
)
5. Modulus Assignment (%=
)
6. Exponentiation Assignment (**=
)
7. Floor Division Assignment (//=
)
Using Assignment Operators with Other Data Types
Example with Lists
You can use the +=
operator to append elements to a list.
Example with Strings
You can also use +=
to concatenate strings.
Summary of Assignment Operators:
=
: Basic assignment operator.+=
: Adds and assigns.-=
: Subtracts and assigns.*=
: Multiplies and assigns./=
: Divides and assigns (result is a float).%=
: Modulus and assigns.**=
: Exponentiation and assigns.//=
: Floor division and assigns.
These assignment operators help to simplify your code by combining operations with assignment in a more concise manner.