











Truth Value Testing in Python
Truth Value Testing
We can use any way to check the truth value of an object . By using ‘If’ statement or ‘While’ statement the checking can be done.
By default, an object is considered true unless its class defines either a __bool__() method that returns False or a __len__ method that returns zero, when called with the object.
Example :
- x=1
- bool(x)=True
- x=1
- if(x==1):
- print(‘True’)
- if(x==1):


Truth Value Testing :
- The truth value 0 is equivalent to False and 1 is same as True.
- When a variable contains different values like 0, 0.0, Fraction(0, 1), Decimal(0), then it signifies the False Value.
- Truth value of an empty sequence is False.


Code :
#python Program
#The class Prep has no __bool__ method, so default value of it is True
class Prep:
def __init__(self):
print(‘This is class Prep’)
p_obj = Prep()
if p_obj:
print(‘It is True’)
else:
print(‘It is False’)
#The class Insta has __bool__ method, which is returning false value
class Insta:
def __init__(self):
print(‘This is class Insta’)
def __bool__(self):
return False
I_obj = Insta()
if I_obj:
print(‘It is True’)
else:
print(‘It is False’)
Tupl = (4,7, 8,41) # Some elements are available, so it returns True
if Tupl:
print(‘Not Empty’)
else:
print(‘Empty’)
lis = [] # No element is available, so it returns False
if lis:
print(‘Not Empty’)
else:
print(‘Empty’)
Output:
This is class Prep
It is True
This is class Insta
It is False
Not Empty
Empty
Login/Signup to comment