python14_运算符复合赋值
复合赋值缩写
A = 7
B = 3
C = "hello"
D = "world"
E = True
F = False
# 加法赋值运算符,7 +3 = 10
def add1(a, b):
a += b # 等同于a = a + b
return a
# 字符串加法赋值运算符,hello + world = helloworld
def add2(c, d):
c += d # 等同于字符串拼接,c = c + d
return c
# 减法赋值运算符 ,7-3 = 4
def del1(a, b):
a -= b # 等同于a = a - b
return a
# 乘法赋值运算符,7*3 = 21
def mul1(a, b):
a *= b # 等同于a = a * b
return a
# 幂运算赋值,7**2=49
def mul2(a, b):
a **= b # 等同于a = a ** b
return a
# 位异或赋值,7 ^ 3 = 5,将7和3转换成二进制,7是0111,3是0011,相同位是0,不同位是1,得到结果是0100,算成10进制,就是0*2^3+1*2^2+0*2^1+0*2^0=4
def mul3(a, b):
a ^= b # 等同于a = a ^ b
return a
# 浮点除赋值,7/3 = 2.3333333333333335
def div1(a, b):
a /= b # 等同于a = a / b
return a
# 整除赋值,7//3 = 2
def div2(a, b):
a //= b # 等同于a = a // b
return a
# 取余赋值, 7 % 3 = 1
def div3(a, b):
a %= b
return a
# 左移赋值,7 << 3 = 56,
# 7 << 3的算法:将7转换为二进制,值是111,左移动3位,是111000,最终换成10进制,等同于1*2^5+1*2^4+1*2^3+0*2^2+0*2^1+0*2^0就是56
def left(a, b):
a <<= b # 等同于a = a << b
return a
# 右移赋值,7 >> 3 = 1
# 7 >> 3的算法:将7转换为二进制,值是111,右移动3位,是0,最终换成10进制,就是0
def right(a, b):
a >>= b # 等同于a = a >> b
return a
# 位或赋值,true | false = true
def or1(a, b):
a |= b # 等同于a = a | b
return a
# 位与赋值,true & false = false
def and1(a, b):
a &= b # 等同于a = a & b
return a
if __name__ == "__main__":
print(f"{A} += {B}输出结果为:{add1(A, B)}") # A += B,实际等同于A = A + B
print(f"{C} += {D}输出结果为:{add2(C, D)}") # C += D,实际等同于C = C + D
print(f"{A} -= {B} 输出结果为:{del1(A, B)}") # A -= B,实际等同于A = A - B
print(f"{A} *= {B}的输出结果为{mul1(A, B)}") # A *= B,实际等同于A = A * B
print(f"{A} **= {B}的输出结果为{mul2(A, B)}") # A **= B,实际等同于A = A ** B
print(f"{A} /= {B}的输出结果为{div1(A, B)}") # A /= B,实际等同于A = A / B
print(f"{A} //= {B}的输出结果为{div2(A, B)}") # A //= B,实际等同于A = A // B
print(f"{A} %= {B}的输出结果为{div3(A, B)}") # A %= B,实际等同于A = A % B
print(f"{A} <<= {B}的输出结果为{left(A, B)}") # A <<= B,实际等同于A = A << B
print(f"{A} >>= {B}的输出结果为{right(A, B)}") # A >>= B,实际等同于A = A >> B
print(f"{E} | {F}的输出结果为{or1(E, F)}") # E |= F,实际等同于E = E | F
print(f"{E} & {F}的输出结果为{and1(E, F)}") # E &= F,实际等同于A = E & F
print(f"{A} ^= {B}的输出结果为{mul3(A, B)}") # A ^= B,实际等同于A = A ^ B
执行结果