Assignment Operators
Assignment operators are used to assign value to the variable. Assign operator is denoted by = symbol. For example, name = "Jessa" here, we have assigned the string literal 'Jessa' to a variable name. Also, there are shorthand assignment operators like a+=2 in Python.
| Operator | Description | Example | Equivalent To |
|---|---|---|---|
= |
Assign value of right side of expression to left side operand | x = y + z |
x = y + z |
+= |
Add and Assign: Add right side operand with left side operand and then assign to left operand | a += b |
a = a + b |
-= |
Subtract AND: Subtract right operand from left operand and then assign to left operand | a -= b |
a = a - b |
*= |
Multiply AND: Multiply right operand with left operand and then assign to left operand | a *= b |
a = a * b |
/= |
Divide AND: Divide left operand with right operand and then assign to left operand | a /= b |
a = a / b |
%= |
Modulus AND: Takes modulus using left and right operands and assign result to left operand | a %= b |
a = a % b |
//= |
Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operand | a //= b |
a = a // b |
**= |
Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand | a **= b |
a = a ** b |
&= |
Performs Bitwise AND on operands and assign value to left operand | a &= b |
a = a & b |
|= |
Performs Bitwise OR on operands and assign value to left operand | a |= b |
a = a | b |
^= |
Performs Bitwise XOR on operands and assign value to left operand | a ^= b |
a = a ^ b |
>>= |
Performs Bitwise right shift on operands and assign value to left operand | a >>= b |
a = a >> b |
<<= |
Performs Bitwise left shift on operands and assign value to left operand | a <<= b |
a = a << b |
Example:
x = 10 # basic assignment
x += 5 # same as x = x + 5 → x is now 15
x -= 3 # same as x = x - 3 → x is now 12
x *= 2 # same as x = x * 2 → x is now 24
x /= 4 # same as x = x / 4 → x is now 6.0
x //= 2 # same as x = x // 2 → x is now 3.0
x %= 2 # same as x = x % 2 → x is now 1.0
x **= 3 # same as x = x ** 3 → x is now 1.0