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() 函数的基本用法。如果数字不为零,则认为 true。因此,下面的代码将返回 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
The result of bool operation on negative num: True
The result of bool operation on 0: False
示例:使用 bool() 检查空字符串
在下面的代码中,我们有两个字符串,bool() 函数用于检查给定的字符串是空的还是非空的。由于任何非空字符串都被视为 True,因此此函数将为空字符串返回 False,对于非空字符串返回 True。
output1 = bool("qikepu")
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
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
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
Is second person is senior citizen: True