零基础学Python(第2版)
上QQ阅读APP看书,第一时间看更新

2.5.3 逻辑运算符和逻辑表达式

逻辑表达式是用逻辑运算符和变量连接起来的式子。任何语言的逻辑运算符都只有3种——逻辑与、逻辑或和逻辑非。C、Java语言的逻辑运算符用 & & 、||、!表示,Python采用and、or、not表示。表2-4列出了Python中的逻辑运算符和表达式。

表2-4 Python中的逻辑运算符和表达式

下面的代码演示了逻辑表达式的运算。


01     # 逻辑运算符
02     print( not True)
03     print( False and True)
04     print (True and False)
05     print (True or False)

【代码说明】

·第2行代码,True的逻辑非为False。输出结果:False

·第3行代码,检测到and运算符左侧的False,就直接返回False。输出结果:False

·第4行代码,检测到and运算符左侧为True,然后继续检测右侧,右侧的值为False,于是返回False。输出结果:False

·第5行代码,or运算符的左侧为True,于是返回True。输出结果:True

逻辑非的优先级大于逻辑与和逻辑或的优先级,而逻辑与和逻辑或的优先级相等。逻辑运算符的优先级低于关系运算符,必须先计算关系运算符,然后再计算逻辑运算符。下面这段代码演示了逻辑运算符、关系运算符和算术运算符的优先级别。


01     # 逻辑表达式的优先级别
02     print( "not 1 and 0 =>", not 1 and 0)
03     print( "not (1 and 0) =>", not (1 and 0))
04     print ("(1 <= 2) and False or True =>", (1 <= 2) and False or True)
05     print ("(1 <= 2) or 1 > 1 + 2 =>", 1 <= 2, "or", 1 > 2, "=>", (1 <= 2) or (1 < 2))

【代码说明】

·第2行代码,先执行not 1,再执行and运算。输出结果:


not 1 and 0 => False

·第3行代码,先执行括号内的1 and 0,再执行not运算。输出结果:


not (1 and 0) => True

·第4行代码,先执行1<=2的关系运算表达式,再执行and运算,最后执行or运算。输出结果:


(1 <= 2) and False or True => True

·第5行代码,先执行1<=2的关系运算表达式,再执行表达式1>1+2,最后执行or运算。输出结果:


(1 <= 2) or 1 > 1 + 2 => True or False => True