1. Python中的not and or简介:
在Python中and/not/or都是布尔值运算符,即返回TRUE(真)和FALSE(假)的运算结果,接下来我们用几个例子分别简单看一下这三种运算符。
(1) A and B:如果A与B中有一个为FALSE则最终结果为FALSE
A值 | B值 | A and B值 |
TRUE | TRUE | TRUE |
TRUE | FALSE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | FALSE |
(2) A or B:如果A与B中有一个为TRUE则最终结果为TRUE
A值 | B值 | A or B值 |
TRUE | TRUE | TRUE |
TRUE | FALSE | TRUE |
FALSE | TRUE | TRUE |
FALSE | FALSE | FALSE |
(3) not A:对A取反向值,比如A为TRUE则not A为FALSE
A值 | not A值 |
TRUE | FALSE |
FALSE | TRUE |
2. Python中的not and or优先级说明
优先级是 not > and > or,这和多数编程语言还有SQL类似。具体举个例子如下
print(not 1>3 or 4>2 and 7>8)
解析:首先1>3为FALSE,4>2为TRUE,7>8为FALSE。所以表达式可以转换为not FALSE or TRUE and FALSE。根据上文说的优先级,先计算not FALSE=TRUE,进而转换表 达式继续为TRUE or TRUE and FALSE,然后计算TRUE and FALSE=FALSE,表达 式最后变为TRUE or FALSE=TRUE