布尔操作符一共有3个( and
、 or
和 not
),用于比较布尔值。
像比较操作符一样,它们将这些表达式求值为一个布尔值。
True and True
True
True and False
False
“真值表”显示了布尔操作符的所有可能结果。下表是操作符 and
的真值表。
表达式 | 求值为 |
True and True | True |
True and False | False |
False and True | False |
False and False | False |
False or True
True
False or False
False
可以在 or
操作符的真值表中看到每一种可能的结果,如下表所示。
表达式 | 求值为 |
True and True | True |
True and False | True |
False and True | True |
False and False | False |
和 and
和 or
不同, not
操作符只作用于一个布尔值(或表达式)。
not
操作符求值为相反的布尔值。
not True
False
not not not not True
True
就像在说话和写作中使用双重否定,可以嵌套 not
操作符 0
,
虽然在真正的程序中并不经常这样做。下表展示了 not
的真值表。
表达式 | 求值为 |
not True | False |
not False | True |
(4 < 5) and (5 < 6)
True
(4 < 5) and (9 < 6)
False
(1 == 2) or (2 == 2)
True
计算机将先求值左边的表达式,然后再求值右边的表达式。知道两个布尔值后, 它又将整个表达式再求值为一个布尔值。 也可以在一个表达式中使用多个布尔操作符,与比较操作符一起使用。
2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
和算术操作符一样,布尔操作符也有操作顺序。
布尔操作符的优化度在算术操作符和比较操作符之后,
Python 先求值 not
操作符,然后是 and
操作符,之后是 or
操作符。