跳到主要内容

Python bool() 函数

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

示例-

test = 1

# 返回 1 的布尔值
print(test, '是', bool(test))

# 输出:1 是 True

bool() 语法

bool() 的语法是:

bool(argument)

bool() 参数

bool() 方法接受单个参数:

  • argument - 返回其布尔值的参数

bool() 返回值

bool() 方法返回:

  • False - 如果参数是 的,False0None
  • True - 如果参数是 任何数字(除了0),True字符串

示例 1:带有 True 参数的 Python bool()

test = 254
# bool() 用于整数
print(test, '是', bool(test))

test1 = 25.14
# bool() 用于浮点数
print(test1, '是', bool(test1))

test2 = 'Python 是最好的'
# bool() 用于字符串
print(test2, '是', bool(test2))

test3 = True
# bool() 用于 True
print(test3, '是', bool(test3))

输出

254 是 True
25.14 是 True
Python 是最好的 是 True
True 是 True

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

这里,该方法对于像 2525.14'Python 是字符串'True 这样的参数返回 True 值。

示例 2:带有 False 参数的 bool()

test = []
# bool() 用于空参数
print(test, '是' ,bool(test))

test1 = 0
# bool() 用于零
print(test1, '是' ,bool(test1))

test2 = None
# bool() 用于 None
print(test2, '是' ,bool(test2))

test3 = False
# bool() 用于 False
print(test3, '是' ,bool(test3))

输出

[] 是 False
0 是 False
None 是 False
False 是 False

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

推荐阅读: