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.

In Truth and Lie Puzzle, there are two tribes on Mars

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. 

Example :

  • x=1
    • bool(x)=True
  • x=1
    • if(x==1):
      • print(‘True’)
implementation of truth value testing in python

Code :

Run
#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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription