freeCodeCamp/guide/chinese/python/boolean-operations/index.md

1.5 KiB
Raw Blame History

title localeTitle
Python Boolean Operations Python布尔运算

and or not

Python Docs - 布尔运算

这些是布尔运算,按升序排序:

操作|结果|笔记
--------- | ------------------------------------ | -----
x或y |如果x为假则为y否则为x | 1
x和y |如果x为假则为x否则为y | 2
不是x |如果x为假则为True否则为False | 3

笔记:

  1. 这是一个短路运算符因此只有在第一个参数为False时才会计算第二个参数。
  2. 这是一个短路操作符因此只有在第一个参数为True时才会计算第二个参数。
  3. 没有比非布尔运算符更低的优先级因此不是a == b被解释为不是a == b而a ==不是b是语法错误。

例子:

not

>>> not True 
 False 
 >>> not False 
 True 

and

>>> True and False    # Short-circuited at first argument. 
 False 
 >>> False and True    # Second argument is evaluated. 
 False 
 >>> True and True     # Second argument is evaluated. 
 True 

or

>>> True or False    # Short-circuited at first argument. 
 True 
 >>> False or True    # Second argument is evaluated. 
 True 
 >>> False or False   # Second argument is evaluated. 
 False