हम किसी भी ऑब्जेक्ट का उपयोग ट्रुथ वैल्यू टेस्ट करने के लिए कर सकते हैं। if या while स्टेटमेंट में कंडीशन प्रदान करके चेक किया जा सकता है।
जब तक कोई क्लास मेथड __bool__() False नहीं लौटाता या __len__() मेथड 0 नहीं लौटाता, हम उस ऑब्जेक्ट की ट्रुथ वैल्यू को True मान सकते हैं।
किसी कॉन्स्टेंट की वैल्यू False होती है जब वह False या None हो।
जब कोई वेरिएबल 0, 0.0, Fraction(0, 1), Decimal(0), 0j जैसे मान रखता है, तो यह फाल्स वैल्यू दर्शाता है।
खाली सीक्वेंस '', [], (), {}, set(0), range(0) की ट्रुथ वैल्यू False होती है।
ट्रुथ वैल्यू 0 False के समतुल्य है और 1 True के समान है।
उदाहरण कोड
class A:
# क्लास A में कोई __bool__ मेथड नहीं है, इसलिए इसका डिफ़ॉल्ट मान 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:
# क्लास B में __bool__ मेथड है, जो फाल्स मान लौटाता है
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 = [] # कोई एलिमेंट नहीं है, इसलिए यह फाल्स लौटाता है
if myList:
print('It has some elements')
else:
print('It has no elements')
mySet = (10, 47, 84, 15) # कुछ एलिमेंट्स हैं, इसलिए यह ट्रू लौटाता है
if mySet:
print('It has some elements')
else:
print('It has no elements')आउटपुट
This is class A It is True This is class B It is False It has no elements It has some elements