Tutorial Study Image

Python bool()

Python 中的 bool 函数接收一个值作为输入,并根据布尔约定返回其布尔值,即 True 或 False。


bool([value]) #where value any object,like String,List,Number etc.
 

bool() 参数

bool 函数只接受一个参数。如果传入一个值作为参数,将返回其等效的布尔值,即 True 或 False。

参数 描述 必需/可选
值或空 Bool 只接受一个参数,如果未传入参数则返回 False。 可选

bool() 返回值

传入除表中提及的输入之外的任何其他输入,都将返回 True。

输入 输出
None False
False False
值为零的数字 False
空的可迭代对象,如 ()、{}、[] 等 False
具有返回 0/False 的 __len__ 或 __bool__ 方法的类 False

bool() 示例

将字符串作为参数传入

eg_string = ‘0’
print(bool(eg_string))

输出

True

传入包含 False 可迭代对象的迭代对象

iterable = [False]
print(bool(iterable))

输出

True

传入空迭代对象

empty_iterable = []
print(bool(empty_iterable))

输出

False