Python 真值测试
什么是真值
我们可以使用任何对象来测试真值。通过在if或while语句中提供条件,可以进行检查。
直到类方法bool()返回 False 或len()方法返回0,我们可以认为该对象的真值是 True 。
- 常量的值为False,当它是 False 或 None 时。
-
当变量包含不同的值如0,0.0,Fraction(0,1),Decimal(0),0j时,表示为False值。
-
空序列”,[],(),{},set(0),range(0)的真值为 False 。
1和0的真值
真值0等同于False,而1等同于True。让我们看看真值,即1的真值为True –
a = 1, then
bool(a) = True
让我们来看看真值的反面,即0的真值是False –
a = 0, then
bool(a) = False
让我们来看另一个快速的示例。1的真值为True-
a = 1
if(a==1)
print(“True”)
0的真值为False –
a = 0
if(a==0)
print(“False”)
Python 真值测试示例
让我们来看一个完整的示例 –
示例
class A:
# The class A has no __bool__ method, so default value of it is True
def __init__(self):
print('This is class A')
a_obj = A()
if a_obj:
print('It is True')
else:
print('It is False')
class B:
# The class B has __bool__ method, which is returning false value
def __init__(self):
print('This is class B')
def __bool__(self):
return False
b_obj = B()
if b_obj:
print('It is True')
else:
print('It is False')
myList = []
# No element is available, so it returns False
if myList:
print('It has some elements')
else:
print('It has no elements')
mySet = (10, 47, 84, 15)
# Some elements are available, so it returns True
if mySet:
print('It has some elements')
else:
print('It has no elements')
输出
This is class A
It is True
This is class B
It is False
It has no elements
It has some elements