Assignment Operators
Assignment operators are used to assign values to variables.
| Operator | Description | Example | Equivalent to |
|---|---|---|---|
= |
Assign value of right side of expression to left side operand | x = 2 |
x = 2 |
+= |
Add right-side operand with left side operand and then assign to left operand | x += 2 |
x = x + 2 |
-= |
Subtract right operand from left operand and then assign to left operand | x -= 2 |
x = x - 2 |
*= |
Multiply right operand with left operand and then assign to left operand | x *= 2 |
x = x * 2 |
/= |
Divide left operand with right operand and then assign to left operand | x /= 2 |
x = x / 2 |
%= |
Takes modulus using left and right operands and assign the result to left operand | x %= 2 |
x = x % 2 |
//= |
Divide left operand with right operand and then assign the value(floor) to left operand | x //= 2 |
x = x // 2 |
**= |
Calculate exponent(raise power) value using operands and assign value to left operand | x **= 2 |
x = x ** 2 |
&= |
Performs Bitwise AND on operands and assign value to left operand | x &= 2 |
x = x & 2 |
&124;= |
Performs Bitwise OR on operands and assign value to left operand | x &124;= 2 |
x = x &124; 2 |
^= |
Performs Bitwise XOR on operands and assign value to left operand | x ^= 2 |
x = x ^ 2 |
>>= |
Performs Bitwise right shift on operands and assign value to left operand | x >>= 2 |
x = x >> 2 |
<<= |
Performs Bitwise left shift on operands and assign value to left operand | x <<= 2 |
x = x << 2 |
Examples
Assign
a = 2
b = 3
result = a + b
print(result) # 5Add and Assign
a = 2
b = 3
a += b # a = a + b
print(a) # 5Subtract and Assign
a = 2
b = 3
a -= b # a = a - b
print(a) # -1Multiply and Assign
a = 2
b = 3
a *= b # a = a * b
print(a) # 6Divide and Assign
a = 2
b = 3
a /= b # a = a / b
print(a) # 0.6666666666666666Modulus and Assign
a = 2
b = 3
a %= b # a = a % b
print(a) # 2Divide (floor) and Assign
a = 2
b = 3
a //= b # a = a // b
print(a) # 0Exponent and Assign
a = 2
b = 3
a **= b # a = a ** b
print(a) # 8Bitwise AND and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a &= b # a = a & b
print(a) # 2 (0010)Bitwise OR and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a |= b # a = a | b
print(a) # 3 (0011)Bitwise XOR and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a ^= b # a = a ^ b
print(a) # 1 (0001)Bitwise Right Shift and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a >>= b # a = a >> b
print(a) # 0 (0000)Bitwise Left Shift and Assign
a = 2 # 2 (0010)
b = 3 # 3 (0011)
a <<= b # a = a << b
print(a) # 16 (1000)