Function Name:
bool(object)
Function Overview:
- The bool() function converts any object into a Boolean value.
- The Boolean value returned is either True or False.
When an object evaluates to False in Python?
-
If the object has a value None, bool() function will return false
- If the object has a value False, bool() function will return false
- If the value of the object is zero bool() will return false. Zero could be from any numeric type like int, floating point, complex type or a user defined type.
- Empty sequences such as empty lists and empty mappings like empty dictionaries.
- If the object belongs to a user defined type and the __bool__() method defined for such object returns False
- If the object belongs to a user defined type and the __len__() method defined for such object returns zero
When an object evaluates to True Python?
When all of the above mentioned False criteria fail, the bool() function will return True.
Examples:
Example for python bool() function:
x = 65 y = 0 z = None listObject = [1, 1, 2, 3, 5, 8]
print(bool(x)) print(bool(y)) print(bool(z)) print(bool(listObject)) |
Example output from python bool() function:
True False False True |
Example for objects evaluating to Boolean values:
# False by default visibility = False;
if (visibility): print("Yes...visibile") else: print("No...Not visibile")
# None values evaluate to false initState = None if(initState): print("Yes...Initialized") else: print("No...Not initialized")
#Custom int class class SpecialInt: myVal=0
def __init__(self, aVal_in): self.myVal = aVal_in
def __bool__(self): if(self.myVal): return True else: return False
SpecialIntObject = SpecialInt(1) if(SpecialIntObject): print("SpecialIntObject evaluates to true") else: print("SpecialIntObject evaluates to false")
listObject = [1,2,3] emptyList = []
if(listObject): print("List with elements evaluate to true")
if(emptyList): print("Strange") else: print("Empty list evaluate to false") |
Example output for objects evaluating to Boolean values:
No...Not visibile No...Not initialized SpecialIntObject evaluates to true List with elements evaluate to true Empty list evaluate to false |