if (n := len(a))
> 10
print(f"List is too long({n} elements, expected <= 10)")
四 位运算符
运算符
作用
&
按位与
|
按位或
^
按位异或
~
按位取反
<<
左移
>>
右移
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c = 0
c = a & b # c = 12
c = a | b # c = 61
c = a ^ b # c = 49
c = ~a # c = -61
c = a << 2 # c = 240 向左移动一位,相当于乘以 2
c = a >> 2 # c = 15 向右移动一位,相当于除以 2
五 逻辑运算符
a = 10, b=11
运算符
作用
实例
and
x and y 逻辑与:如果 x 为 False,返回的 x 值 否则返回 y 的值
(a and b)返回 20
or
x or y 逻辑或:如果 x 为 True,返回的 x 值 否则返回 y 的值
(a or b)返回 10
not
not x 逻辑非
not(a and b)返回 False
六 成员运算符
运算符
作用
in
如果在指定的序列中找到值返回 True,否则返回 False
not in
如果在指定的序列中没有找到值返回 True,否则返回 False
a = 6
b = 66
list = [1, 2, 3, 4, 5]
if (a in list)
print("a in list")
else:
print("a not in list") #结果
if (b not in list)
print("b not in list") #结果
else:
print("b in list")
七 身份运算符
运算符
实例
is
x is y,类似 id(x)==id(y),如果引用的是同一个对象则返回True,否则返回False
is not
x is not y,类似 id(x)!=id(y),如果引用的是同一个对象则返回True,否则返回False