Python Truth Value Testing


What is Truth Value

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.

Truth Value of 1 and 0

The truth value 0 is equivalent to False and 1 is same as True. Let’s see the truth value i.e. the truth value of 1 is True −

a = 1, then
bool(a) = True

Let’s see the opposite of the truth value i.e. the truth value of 0 is False −

a = 0, then
bool(a) = False

Let us see another quick example. The truth value of 1 is True −

a = 1

if(a==1)
   print(“True”)

The truth value of 0 is False −

a = 0

if(a==0)
   print(“False”)

Python Truth Value Testing Example

Let us see a complete example −

Example

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

Updated on: 12-Aug-2022

806 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements