‘and’、‘or’和‘not’的优先级是 not>and>or
逻辑运算符的本质
在 Python 中,and 和 or 不一定会计算右边表达式的值,有时候只计算左边表达式的值就能得到最终结果。
另外,and 和 or 运算符会将其中一个表达式的值作为最终结果,而不是将 True 或者 False 作为最终结果。
以上两点极其重要,了解这两点不会让你在使用逻辑运算的过程中产生疑惑。
对于 and 运算符,两边的值都为真时最终结果才为真,但是只要其中有一个值为假,那么最终结果就是假,所以 Python 按照下面的规则执行 and 运算:
- 如果左边表达式的值为假,那么就不用计算右边表达式的值了,因为不管右边表达式的值是什么,都不会影响最终结果,最终结果都是假,此时 and 会把左边表达式的值作为最终结果。
- 如果左边表达式的值为真,那么最终值是不能确定的,and 会继续计算右边表达式的值,并将右边表达式的值作为最终结果。
对于 or 运算符,情况是类似的,两边的值都为假时最终结果才为假,只要其中有一个值为真,那么最终结果就是真,所以 Python 按照下面的规则执行 or 运算:
- 如果左边表达式的值为真,那么就不用计算右边表达式的值了,因为不管右边表达式的值是什么,都不会影响最终结果,最终结果都是真,此时 or 会把左边表达式的值作为最终结果。
- 如果左边表达式的值为假,那么最终值是不能确定的,or 会继续计算右边表达式的值,并将右边表达式的值作为最终结果。
对于普通的bool表达式便不展示了,这里主要探究数字之间的逻辑运算。
a=23
b=0
c=12
d=0
print (a and b) # 0
print (b and a) # 0
print (c and d) # 0
print (d and c) # 0
print (not a) # False
print (not b) # True
print (a or b) # 23
print (b or a) # 23
print (c or d) # 12
print (d or c) # 12
#----------------------------------
a=-23
b=32
c=12
d=-24
print (a and b) # 32
print (b and a) # -23
print (c and d) # -24
print (d and c) # 12
print (not a) # False
print (not b) # False
print (a or b) # -23
print (b or a) # 32
print (c or d) # 12
print (d or c) # -24
个人笔记: