实验1:
assert False and False or True == True # 一个True就能导致整个表达式输出True 应该后计算or
assert True or False and False == True # 交换前后顺序,依然先计算or
assert False and True or False == False # 中间的True无效,应该先算and
assert False or True and False == False # 交换and和or不影响结果
# 用`&` `|` 代替`and` `or`依然能运行
更多的and
和or
连接起来,也是先算and
再算or
,结论:and
比or
的优先级高,另外逻辑运算符not
的优先级比and
还要高
实验2:
def func(x):
print('func', x)
return 'return from func'
a = True or func('a')
b = False or func('b') # 显示 func b
c = True and func('c') # 显示 func c
d = False and func('d')
# 用`&` `|` 代替`and` `or`会发生错误:
# TypeError: unsupported operand type(s) for |: 'bool' and 'str'
print(f'a {a}\n') # 显示 a True
print(f'b {b}\n') # 显示 b return from func
print(f'c {c}\n') # 显示 c return from func
print(f'd {d}\n') # 显示 d False
print(False or None) # 显示 None
print(True and 1) # 显示 1
or
遇到一个判断为等价True的值,表达式整体为当前值,丢掉剩余部分。
and
遇到一个判断为等价False的值,表达式整体为当前值,丢掉剩余部分。
如果一直没有遇到,则返回最后一个值。
一串or
连接的表达式中,只要有一个为True
,结果就为True
;所有都为False
时,表达式才为False
。
一串and
连接的表达式中,只要有一个False
,结果就为False
;所有都为True
时,表达式才为True
。
合理调整表达式的顺序,可以加快运算速度,避免程序出错。
这种运算称为短路逻辑
实践:删除列表或字典中的元素,如果存在则删除,如果不存在则忽略
s = {1, 'a', None}
print('before', s) # 显示before {1, 'a', None}
rm2 = 1 in s and not s.remove(1) # 注意: 判断和移除时的元素要相同
rm3 = 2 in s and not s.remove(2) # not 是为了方便
print('after ', s) # 显示after {'a', None}
print(f'rm2:{rm2}, rm3:{rm3}') # 显示rm2:True, rm3:False
大家有没有想到更好的实现方法,可以交流一下。