Python bool() 函数

2024年9月26日 | 阅读 3 分钟

bool() 函数是 Python 的内置函数之一,它根据输入的参数输出布尔值。该函数接受一个参数,并返回布尔值 True 或 False。Python 的 bool() 方法使用标准的真值测试过程将值转换为布尔值(True 或 False)。

语法

参数

bool() 函数可以不带参数调用。如果您不传递任何参数,bool() 将返回 False。

通常,bool() 接受一个参数值。

返回

bool() 返回:

  • 如果省略值或值为 false 且条件未满足,则返回 False。
  • 如果值为 true 且条件满足,则返回 True。

Python bool() 函数示例 1

代码

输出

[] is False
[] is False
[0] is True
0.0 is False
None is False
True is True
Easy string is True

Python bool() 函数示例 2

在 if-else 语句中使用 bool() 函数。

代码

输出

number is less than or equal to 15

在上面的代码中,如果条件为真或假,则执行相应的块。现在,让我们在下面的示例中查看值到布尔值的显式转换。

# 使用 bool() 函数将条件转换为布尔值

代码

输出

number is less than or equal to 15

Python bool() 函数示例 3

1. 使用 bool() 函数检查值是 True 还是 False

代码

输出

True

2. 检查空字符串是 True 还是 False

代码

输出

False

3. 检查零值是 True 还是 False

代码

输出

False

结论

总而言之,bool() 函数是 Python 中处理布尔值的有用工具。它可以用来将任何值显式转换为布尔值,也可以用来检查一个值是真还是假。


下一个主题Python 内置函数