Boolean data and the bool() function
All objects can have a mapping to the Boolean domain of values: True
and False
. All of the built-in classes have this mapping defined. When we define our own classes, we need to consider this Boolean mapping as a design feature.
The built-in classes operate on a simple principle: if there's clearly no data, the object should map to False
. Otherwise, it should map to True
. Here are some detailed examples:
The
None
object maps toFalse
.For all of the various kinds of numbers, a zero value maps to
False
. All non-zero values areTrue
.For all of the collections (including
str
,bytes
,tuple
,list
,dict
,set
, and so on) an empty collection isFalse
. A non-empty collection isTrue
.
We can use the bool()
function to see this mapping between object and a Boolean:
>>> red_violet= (192, 68, 143) >>> bool(red_violet) True >>> empty = () >>> type(empty) <class 'tuple'> >>> bool(empty) False
We've created a simple sequence...