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- 如果 argument 为空、False、0 或 NoneTrue- 如果 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() 方法,并带有各种参数,如整数、浮点数和字符串。
在这里,该方法对 25、25.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() 方法对 0、None、False 和 [] 等参数返回 False 值。
另请阅读
