Python 中的 bool()
pythonserver side programmingprogramming更新于 2025/9/22 1:48:17
Python 中的 bool() 返回提供给它的参数的布尔值。该参数可以是以下任意一种,结果按照以下条件进行。除了这里提到的值,其余值都返回 True。
当传递的参数值如下所示时,将返回 False −
无
False 条件
任何数字类型的零
空序列 ()、[] 等。
空映射,如 {
具有 __bool__() 或 __len()__ 方法的类的对象,它们返回 0 或 False
示例
在下面的程序中,我们说明了所有此类示例场景。
print("None gives : ",bool(None))
print("True gives : ",bool(True))
print("Zero gives: ",bool(0))
# 表达式求值为真
print("Expression evaluating to True: ",bool(0 == (18/3)))
# 表达式计算结果为假
print("Expression evaluating to False: ",bool(0 == (18%3)))
s = ()
print("An mpty sequence: ",bool(s))
m = {}
print("An emty mapping: ",bool(m))
t = 'Tutoriaslpoint'
print("A non empty string: ",bool(t))
输出
运行上述代码得到以下结果 −
None gives : False True gives : True Zero gives: False Expression evaluating to True: False Expression evaluating to False: True An mpty sequence: False An emty mapping: False A non empty string: True
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

