Python assignment operators
Created By: chatGPT
Assignment operators in Python are used to assign values to variables. These operators allow you to perform operations while assigning values in a more concise manner. Here are some of the most commonly used assignment operators:
1. Basic assignment operator (
=
): This operator simply assigns the value on the right to the variable on the left.x = 10
2. Addition assignment operator (
+=
): This operator adds the right operand to the left operand and assigns the result to the left operand.x += 5 # Equivalent to x = x + 5
3. Subtraction assignment operator (
-=
): This operator subtracts the right operand from the left operand and assigns the result to the left operand.x -= 3 # Equivalent to x = x - 3
4. Multiplication assignment operator (
*=
): This operator multiplies the left operand by the right operand and assigns the result to the left operand.x *= 2 # Equivalent to x = x * 2
5. Division assignment operator (
/=
): This operator divides the left operand by the right operand and assigns the result to the left operand.x /= 4 # Equivalent to x = x / 4
6. Floor division assignment operator (
//=
): This operator performs floor division on the left operand by the right operand and assigns the result to the left operand.x //= 3 # Equivalent to x = x // 3
7. Modulus assignment operator (
%=
): This operator takes the modulus using the left operand and the right operand and assigns the result to the left operand.x %= 2 # Equivalent to x = x % 2
8. Exponentiation assignment operator (
**=
): This operator raises the left operand to the power of the right operand and assigns the result to the left operand.x **= 3 # Equivalent to x = x ** 3
9. Bitwise AND assignment operator (
&=
): This operator performs a bitwise AND operation on the left operand and the right operand and assigns the result to the left operand.x &= 2 # Equivalent to x = x & 2
10. Bitwise OR assignment operator (
|=
): This operator performs a bitwise OR operation on the left operand and the right operand and assigns the result to the left operand.x |= 2 # Equivalent to x = x | 2
11. Bitwise XOR assignment operator (
^=
): This operator performs a bitwise XOR operation on the left operand and the right operand and assigns the result to the left operand.x ^= 2 # Equivalent to x = x ^ 2
Example: Here's a simple example that uses some of these assignment operators in practice:
x = 10
x += 5 # x is now 15
x *= 2 # x is now 30
x //= 3 # x is now 10