Python bool()

bool() 方法接受一个指定参数并返回其布尔值。

示例-

test = 1

# returns boolean value of 1 print(test, 'is', bool(test))
# Output: 1 is True

bool() 语法

bool() 的语法是

bool(argument)

bool() 参数

bool() 方法接受一个参数

  • argument - 返回其布尔值

bool() 返回值

bool() 方法返回

  • False - 如果 argumentFalse0 None
  • True - 如果 argument任何数字 (除了 0)、 True 或一个 字符串

示例 1:Python bool() 与 True 参数

test = 254
# bool() with an integer number print(test, 'is', bool(test))
test1 = 25.14
# bool() with a floating point number print(test1, 'is', bool(test1))
test2 = 'Python is the best'
# bool() with a string print(test2, 'is', bool(test2))
test3 = True
# bool() with True print(test3, 'is', bool(test3))

输出

254 is True
25.14 is True
Python is the best is True
True is True

在上面的示例中,我们使用了 bool() 方法,并带有各种参数,如整数、浮点数和字符串。

在这里,该方法对 2525.14'Python is a String'True 等参数返回 True 值。


示例 2:bool() 与 False 参数

test = []
# bool() with an empty argument print(test, 'is' ,bool(test))
test1 = 0
# bool() with zero print(test1, 'is' ,bool(test1))
test2 = None
# bool() with none print(test2, 'is' ,bool(test2))
test3 = False
# bool() with False print(test3, 'is' ,bool(test3))

输出

[] is False
0 is False
None is False
False is False

在上面的示例中,bool() 方法对 0NoneFalse[] 等参数返回 False 值。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战