1. 程式人生 > >Python學習之基本資料型別 bool值,邏輯運算子

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:

OperationResultNotes
x or yif x is false, then y, else x(1)
x and yif x is false, then x, else y(2)
not xif 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是一個錯誤的語法。