Python – Truth Value Testing

Truth value testing verify whether the value is True or False. In Python, any object can be tested for Truth Value.

What really the Truth Value is? True is the Truth value. But non boolean values doesn’t have true or false values. For example, numbers do not have true or false value. They are simply numbers. Hence all non zero numbers are considered as the value True.

Similarly, if the sequences, collections, sets etc, have any elements then considered as the value True; otherwise (that means if they are empty), considered the value as False.

Class objects are considered as True unless they explicitly returns False or value zero (0) through the methods _bool_() or __len__().

We use these Truth values during conditional check and Boolean operations.

None and False constants have the Truth Value False.

Here are some of the working examples of Truth Value Testing:

>>> 0 = False
  File "", line 1
SyntaxError: can't assign to literal
>>> 0 == False
True
>>> None == True
False
>>> False == False
True
>>> 1 == True
True

A set with elements considered has a Truth Value True.

>>> st = {1, 2, 3}
>>> st == FALSE
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'FALSE' is not defined
>>> st == False
False

An empty tuple has a Truth Value False.

>>> tpl = ()
>>> type(tpl)
<class 'tuple'>
>>> tpl == True
False

/Shijit/

Python – Truth Value Testing

3 thoughts on “Python – Truth Value Testing

Leave a Reply

Your email address will not be published.

Scroll to top