We can use any object to test the truth value. By providing the condition in the if or while statement, the checking can be done.
Until a class method __bool__() returns False or __len__() method returns 0, we can consider the truth value of that object is True.
The value of a constant is False, when it is False, or None.
When a variable contains different values like 0, 0.0, Fraction(0, 1), Decimal(0), 0j, then it signifies the False Value.
The empty sequence ‘‘, [], (), {}, set(0), range(0), Truth value of these elements are False.
The truth value 0 is equivalent to False and 1 is same as True.
Example Code
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')
Output
This is class A It is True This is class B It is False It has no elements It has some elements