Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 to False.

  • For all of the various kinds of numbers, a zero value maps to False. All non-zero values are True.

  • For all of the collections (including str, bytes, tuple, list, dict, set, and so on) an empty collection is False. A non-empty collection is True.

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...