Booleans

Some argue that the Python Boolean type, bool, is numeric in nature because its two values, True and False, are just customized versions of the integers 1 and 0 that print themselves differently. Although that’s all most programmers need to know, let’s explore this type in a bit more detail.

More formally, Python today has an explicit Boolean data type called bool, with the values True and False available as new preassigned built-in names. Internally, the names True and False are instances of bool, which is in turn just a subclass (in the object-oriented sense) of the built-in integer type int. True and False behave exactly like the integers 1 and 0, except that they have customized printing logic—they print themselves as the words True and False, instead of the digits 1 and 0. bool accomplishes this by redefining str and repr string formats for its two objects.

广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元

Because of this customization, the output of Boolean expressions typed at the interactive prompt prints as the words True and False instead of the older and less obvious 1 and 0. In addition, Booleans make truth values more explicit. For instance, an infinite loop can now be coded as while True: instead of the less intuitive while 1:. Similarly, flags can be initialized more clearly with flag = False. We’ll discuss these statements further in Part III.

Again, though, for all other practical purposes, you can treat True and False as though they are predefined variables set to integer 1 and 0. Most programmers used to preassign True and False to 1 and 0 anyway; the bool type simply makes this standard. Its implementation can lead to curious results, though. Because True is just the integer 1 with a custom display format, True + 4 yields 5 in Python:

>>> type(True)
<class 'bool'>
>>> isinstance(True, int)
True
>>> True == 1                # Same value
True
>>> True is 1                # But different object: see the next chapter
False
>>> True or False            # Same as: 1 or 0
True
>>> True + 4                 # (Hmmm)
5

Since you probably won’t come across an expression like the last of these in real Python code, you can safely ignore its deeper metaphysical implications....

We’ll revisit Booleans in Chapter 9 (to define Python’s notion of truth) and again in Chapter 12 (to see how Boolean operators like and and or work).