Python学习之基本数据类型 bool值,逻辑运算符

Truth Value Testing

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__() method that returns zero, when called with the object. [1] Here are most of the built-in objects considered false:

  • constants defined to be false: None and False.
  • zero of any numeric type: 00.00jDecimal(0)Fraction(0, 1)
  • empty sequences and collections: ''()[]{}set()range(0)

Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

翻译:所有的对象都可以表示bool值,不如用if或者while条件,或者像下面的操作一样表示bool值。
一般的,对象默认都是真值,除非这个对象的类定义了__bool__方法且返回False或者是__len__方法返回了0.这里是
python的被默认认为是false的对象。
直接被定义为false值:None或者False
任何数值的0
空的序列或者是集合
操作和内置的函数如果有返回值,大多数情况下都是用0或者False来表示false值,用1或者Ture来表示真值,除非有
其他的状态(重要的异常:bool操作  或和与经常只返回他们其中的一个操作的值)

Boolean Operations — andornot

These are the Boolean operations, ordered by ascending priority:

Operation Result Notes
x or y if x is false, then y, else x (1)
x and y if x is false, then x, else y (2)
not x if x is false, then True, else False (3)

Notes:

  1. This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
  2. This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
  3. not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a== not b is a syntax error.
翻译:bool类型的操作  and or not
这些都是bool类型的操作,按照优先级进行排序
1:这是一个短路运算符,就是说如果想要进行验证第二个表达式只有第一个表达式为Flase
2:这同样是一个短路运算符,只有当第一个为真的时候才会验证第二个。
3:not是所有bool操作中优先级最低的,因此 not a==b 等价于 not (a==b)而且 a==not b是一个错误的语法。

猜你喜欢

转载自blog.csdn.net/rubikchen/article/details/80542092