Python的增广赋值运算符
赋值运算符符是用于将某个值分配给变量的运算符。像通常在Python,我们写“ a = 5 ” 将值 5 赋给变量“a”。增广赋值运算符在Python编程中扮演着特殊的角色。它基本上将算术或按位运算运算符与赋值运算符。因此假设如果我们需要将 7 添加到变量“a”并将结果分配回“a”,那么我们可以使用增广赋值运算符而不是通常写成“ a = a + 7 ”,并将表达式写为“一个+= 7 ”。这里 += 结合了算术加法和赋值的功能。
因此,增强赋值运算符提供了一种执行二元运算并将结果分配回其中一个操作数的简便方法。编写增强运算符的方法就是将二元运算符和赋值运算符一起编写。在Python,我们有几个不同的增强赋值运算符,如 +=、-=、*=、/=、//=、**=、|=、&=、>>=、<<=、%= 和 ^= .让我们借助一些示例代码来看看它们的功能:
1.加法和赋值(+=):这个运算符结合了算术加法和赋值的影响。这里,
a = a + b can be written as a += b
例子:
Python3
# Addition & Assignment
a = 15
b = 20
a += b
print(a)
Python3
# Subtraction & Assignment
a = 107
b = 99
a -= b
print(a)
Python3
# Multiplication & Assignment
a = 12
b = 23
a *= b
print(a)
Python3
# Division & Assignment
a = 56
b = 5
a /= b
print(a)
Python3
# Floor Division & Assignment
a = 56
b = 8
a //= b
print(a)
Python3
# Modulo & Assignment
a = 34
b = 5
a %= b
print(a)
Python3
# Power & Assignment
a = 5
b = 3
a **= b
print(a)
Python3
# Bitwise AND & Assignment
a = 12
b = 10
a &= b
print(a)
Python3
# Bitwise OR and Assignment
a = 12
b = 10
a |= b
print(a)
Python3
# Bitwise XOR and Assignment
a = 12
b = 10
a ^= b
print(a)
Python3
# Bitwise Left Shift and Assignment
a = 17
b = 2
a <<= b
print(a)
Python3
# Bitwise Right Shift and Assignment
a = 17
b = 2
a >>= b
print(a)
35
2. 减法和赋值(-=):这个运算符结合了减法和赋值的影响。
a = a – b can be written as a -= b
例子:
蟒蛇3
# Subtraction & Assignment
a = 107
b = 99
a -= b
print(a)
8
3. 乘法和赋值(*=):这个运算符结合了乘法和赋值的功能。
a = a * b can be written as a *= b
例子:
蟒蛇3
# Multiplication & Assignment
a = 12
b = 23
a *= b
print(a)
276
4. 除法和赋值(/=):该运算符具有除法和赋值的组合功能。
a = a / b can be written as a /= b
例子:
蟒蛇3
# Division & Assignment
a = 56
b = 5
a /= b
print(a)
11.2
5. 楼层划分与赋值(//=):执行楼层划分与赋值的功能。
a = a // b can be written as a //= b
例子:
蟒蛇3
# Floor Division & Assignment
a = 56
b = 8
a //= b
print(a)
7
6. 取模和赋值(%=):这个运算符结合了取模运算符和赋值的影响。
a = a % b can be written as a %= b
例子:
蟒蛇3
# Modulo & Assignment
a = 34
b = 5
a %= b
print(a)
4
7.幂和赋值(**=):这个运算符相当于幂和赋值运算符一起。
a = a**b can be written as a **= b
例子:
蟒蛇3
# Power & Assignment
a = 5
b = 3
a **= b
print(a)
125
8. 按位与与赋值(&=):该运算符结合了按位与运算符和赋值运算符。
a = a & b can be written as a &= b
例子:
蟒蛇3
# Bitwise AND & Assignment
a = 12
b = 10
a &= b
print(a)
8
9. 按位或和赋值(|=):这个运算符结合了按位或和赋值运算符。
a = a | b can be written as a |= b
例子:
蟒蛇3
# Bitwise OR and Assignment
a = 12
b = 10
a |= b
print(a)
14
10. 按位异或和赋值 (^=):这个增强的赋值运算符结合了按位异或运算符和赋值运算符。
a = a ^ b can be written as a ^= b
例子:
蟒蛇3
# Bitwise XOR and Assignment
a = 12
b = 10
a ^= b
print(a)
6
11. 按位左移和赋值(<<=):它将按位左移运算符和赋值运算符的功能放在一起。
a = a << b can be written as a <<= b
例子:
蟒蛇3
# Bitwise Left Shift and Assignment
a = 17
b = 2
a <<= b
print(a)
68
12. 按位右移和赋值(>>=):它将按位右移运算符和赋值运算符的功能放在一起。
a = a >> b can be written as a >>= b
例子:
蟒蛇3
# Bitwise Right Shift and Assignment
a = 17
b = 2
a >>= b
print(a)
4