| Python also supports various simplified (or compound) assignment operators. These operators work similarly to those in PHP, combining an operation with an assignment to make the code more concise. 1. Arithmetic Assignment Operators These operators perform arithmetic and assignment together. - Addition:
a += b is equivalent to a = a + b - Subtraction:
a -= b is equivalent to a = a - b - Multiplication:
a *= b is equivalent to a = a * b - Division:
a /= b is equivalent to a = a / b - Floor Division:
a //= b is equivalent to a = a // b - Modulus:
a %= b is equivalent to a = a % b - Exponentiation:
a **= b is equivalent to a = a ** b
2. Bitwise Assignment Operators These operators apply bitwise operations and assignment in one step. - Bitwise AND:
a &= b is equivalent to a = a & b - Bitwise OR:
a |= b is equivalent to a = a | b - Bitwise XOR:
a ^= b is equivalent to a = a ^ b - Left Shift:
a <<= b is equivalent to a = a << b - Right Shift:
a >>= b is equivalent to a = a >> b
3. Logical Assignment Operators Python doesn’t have explicit logical assignment operators like JavaScript, but logical operations can be combined with assignment using idioms such as conditional expressions. 4. Walrus Operator (Python 3.8+) The walrus operator := assigns a value to a variable as part of an expression. It is helpful in conditional statements and loop structures. Example: if (n := len(some_list)) > 5:
print(f"List has {n} elements.")
Example Usage in Python x = 10
x += 5 # x is now 15
y = 20
y //= 3 # y is now 6 (integer division)
z = 2
z **= 3 # z is now 8 (2^3)
a = 5
a |= 3 # a is now 7 (bitwise OR)
some_list = [1, 2, 3, 4, 5]
if (n := len(some_list)) > 4:
print(f"The list has {n} elements.")
These simplified operators help streamline code in Python, making it easier to read and more efficient. |