
4.4 布尔逻辑运算
布尔逻辑运算是对真和假两种布尔值进行运算,运算后的结果仍然是一个布尔值。Python提供了3种逻辑运算:逻辑与(and)运算、逻辑或(or)运算和逻辑非(not)运算。
4.4.1 逻辑与运算
逻辑与运算表示取与运算,如图4.23所示。

图4.23 逻辑与运算
图中的and为逻辑运算符,用来将x和y进行取与运算,得出布尔值。需要注意的是,and与x和y之间需要有空格。该运算类似于位运算中的位与运算。在位与运算中,同为1时为1,有一个不为1则为0。在Python中,默认1代表True(真),0代表False(假)。逻辑与(and)运算的规则及结果如表4-3所示。
表4.3 逻辑与(and)运算的规则及结果

助记:同为真时为真,有一个为假就为假。
【实例4-28】下面将表达式2+6>7与表达式9>5进行逻辑与运算,并查看结果,代码如下:

代码中,表达式2+6>7的结果为True,表达式9>5的结果也为True。True与True进行逻辑与运算,同时都为True,因此,最终运算结果为True。
4.4.2 逻辑或运算

图4.24 逻辑或运算
逻辑或表示取或运算,如图4.24所示。
图中的or为逻辑运算符,用来将x和y进行取或运算,得出布尔值。需要注意的是,or与x和y之间需要有空格。该运算类似于位运算中的位或运算。逻辑或(or)运算的规则及结果如表4-4所示。
表4.4 逻辑或(or)运算的规则及结果

助记:同为假时为假,有一个为真就为真。
【实例4-29】下面将表达式2+6>7与表达式9<5进行逻辑或运算,并查看结果,代码如下:

代码中,表达式2+6>7的结果为True,表达式9<5的结果为False。True与False进行逻辑或运算,有一个为True,结果就为True。因此,最终运算结果为True。
4.4.3 逻辑非运算

图4.25 逻辑非运算
逻辑非表示取反运算,如图4.25所示。
图中的not为逻辑运算符,用来将y进行取反运算,得出布尔值。需要注意的是,not与y之间需要有空格。逻辑非(not)运算的规则及结果如表4-5所示。
表4.5 逻辑非(not)运算的规则及结果

助记:原为真,现为假;原为假,现为真。
【实例4-30】下面将表达式8**5>8*5进行逻辑非运算,代码如下:

代码中,表达式8**5>8*5的结果为True,对其进行逻辑非运算,最终结果为False。
4.4.4 逻辑运算符优先级
Python进行布尔逻辑运算时,如果运算中存在多个逻辑运算符,则会根据逻辑运算符优先级的高低依次进行运算。Python支持的逻辑运算符优先级(从高到低)如表4-6所示。
表4.6 逻辑运算符优先级

【实例4-31】下面在交互模式中对代码9>2 or 8>12 and 7>21进行运算,并查看运行结果,代码如下:

执行后,得出运算结果如下:

由于or的优先级低于and的优先级,因此首先运算8>12 and 7>21,该运算结果为False,然后运算9>2 or False,最后得出运算结果为True。
在进行布尔运算时,也可以通过使用圆括号(())改变运算符优先级的顺序。例如,上述例子中先运算or的逻辑运算,再运算and的逻辑运算,代码如下:

执行后,运算结果将发生变化。

4.4.5 短路原则
一个运算当中可能会包含多个逻辑运算符,按照默认运算情况,计算机会根据逻辑运算符的优先级进行运算。但是当表达式前面部分已经能确定整个表达式的值时,后面部分就没有计算的必要了。为了减少运算量,Python会使用短路原则进行逻辑运算,它适用于or逻辑运算和and逻辑运算。
1. or逻辑运算的短路原则
or逻辑运算只要有一个为真就为真。短路原则是指,当or的第一个条件为真时,那么or的第二个、第三个甚至更多的条件,无论是真是假,计算机都不需要进行运算了,结果一定为真,如图4.26所示。

图4.26 or短路原则
图中,or左侧的第一个条件为真,计算机将不会运算条件“?1”和条件“?2”的真假,直接得出运算结果为真。
【实例4-32】下面在交互模式中对代码10==0b1010 or 10>16 and 7+8>100进行运算,并查看运行结果,代码如下:

执行后,得出运算结果如下:

代码中的第一个逻辑运算符为or,因此计算机只需要运算or的第一个条件10==0b1010,该条件为True。计算机将不会运算10>16和7+8>100,直接得出结论为True。
2. and逻辑运算的短路原则
and逻辑运算只要有一个为假就为假。短路原则是指,当and的第一个条件为假时,那么and的第二个、第三个甚至更多的条件,无论是真是假,计算机都不需要进行运算了,因为结果一定为假,如图4.27所示。

图4.27 and短路原则
图中,and左侧的第一个条件为假,计算机将不会运算条件“?1”和条件“?2”的真假,直接得出运算结果为假。
【实例4-33】下面在交互模式中对代码3+4>7+8 and 30>4+5 or 20>7进行运算,并查看运行结果,代码如下:

执行后,得出运算结果如下:

代码中的第一个逻辑运算符为and,因此计算机只需要运算and的第一个条件3+4>7+8,该条件为False。计算机将不会运算30>4+5和20>7,直接得出结论为False。