Python bool() 函式



**Python bool() 函式**根據給定物件的真值測試過程的結果返回一個布林值(True 或 False)。如果未提供引數,則該函式返回 False。

物件的真值測試可以使用 if 或 while 條件或布林運算來實現。在布林運算中,使用 __bool__() 和 __len__() 方法。如果一個物件沒有 __bool__() 方法,則呼叫它的 __len__() 方法,該方法返回物件的長度。如果長度為零,則該物件被視為 False,否則被視為 True。

**bool()** 是內建函式之一,您無需匯入任何模組即可使用它。

語法

以下是 Python **bool()** 函式的語法:

bool(object)

引數

Python **bool()** 函式接受一個引數:

  • **object** - 此引數表示一個物件,例如列表、字串、數字或任何表示式。

返回值

Python **bool()** 函式根據給定的輸入返回 True 或 False。

bool() 函式示例

練習以下示例以瞭解如何在 Python 中使用 **bool()** 函式

示例:bool() 函式的使用

以下示例顯示了 Python bool() 函式的基本用法。如果一個數字不為零,則被認為是真。因此,以下程式碼將對零返回 false,對其他數字返回 true。

output1 = bool(111) 
print("The result of bool operation on positive num:", output1) 
output2 = bool(-68) 
print("The result of bool operation on negative num:", output2) 
output3 = bool(0)
print("The result of bool operation on 0:", output3) 

當我們執行以上程式時,它會產生以下結果:

The result of bool operation on positive num: True
The result of bool operation on negative num: True
The result of bool operation on 0: False

示例:使用 bool() 檢查空字串

在以下程式碼中,我們有兩個字串,並且 bool() 函式用於檢查給定的字串是空還是非空。由於任何非空字串都被視為 True,因此此函式將對空字串返回 False,對非空字串返回 True。

output1 = bool("Tutorialspoint") 
print("The result of bool operation on non-empty String:", output1) 
output2 = bool("") 
print("The result of bool operation on an empty String:", output2)

以下是上述程式碼的輸出:

The result of bool operation on non-empty String: True
The result of bool operation on an empty String: False

示例:使用 bool() 函式檢查空列表

以下程式碼顯示瞭如何使用 bool() 函式檢查空列表和非空列表的真值。

output1 = bool([71, 87, 44, 34, 15]) 
print("The result of bool operation on non-empty List:", output1) 
output2 = bool([]) 
print("The result of bool operation on an empty List:", output2) 

上述程式碼的輸出如下:

The result of bool operation on non-empty List: True
The result of bool operation on an empty List: False

示例:演示 bool() 與 __bool()__ 函式

在以下程式碼中,我們將演示如何一起使用 __bool__() 和 bool() 方法來根據一個人的年齡檢查他是否為老年人。

class SeniorCitizen:
   def __init__(self, name, age):
      self.name = name
      self.age = age
   def __bool__(self):
      return self.age > 60

senCitzn1 = SeniorCitizen("Raman", 20)
senCitzn2 = SeniorCitizen("Ramesh", 65)
output1 = bool(senCitzn1)
output2 = bool(senCitzn2)
print("Is first person is senior citizen:", output1)
print("Is second person is senior citizen:", output2) 

以下是上述程式碼的輸出:

Is first person is senior citizen: False
Is second person is senior citizen: True
python_built_in_functions.htm
廣告