8.5. Boolean Values Are Integer Values¶
Just as Python considers the float value 42.0 to be equal to the integer value 42 , it considers the Boolean values True and False to be equivalent to 1 and 0 , respectively. In Python, the bool data type is a subclass of the int data type. (We’ll cover classes and subclasses in Chapter 16.) You can use int() to con- vert Boolean values to integers:
>>> int(False)
0
>>> int(True)
1
>>> True == 1
True
>>> False == 0
True
You can also use isinstance() to confirm that a Boolean value is consid- ered a type of integer:
>>> isinstance(True, bool)
True
>>> isinstance(True, int)
True
The value True is of the bool data type. But because bool is a subclass of int , True is also an int . This means you can use True and False in almost any place you can use integers. This can lead to some bizarre code:
>>> True + False + True + True # Same as 1 + 0 + 1 + 1
3
>>> -True
>>> # Same as -1.
-1
>>> 42 * True # Same as 42 * 1 mathematical multiplication.
42
>>> 'hello' * False # Same as 'hello' * 0 string replication.
''
>>> 'hello'[False] # Same as 'hello'[0]
'h'
>>> 'hello'[True] # Same as 'hello'[1]
'e'
>>> 'hello'[-True] # Same as 'hello'[-1]
'o'
Of course, just because you can use bool values as numbers doesn’t mean you should. The previous examples are all unreadable and should never be used in real-world code. Originally, Python didn’t have a bool data type. It didn’t add Booleans until Python 2.3, at which point it made bool a subclass of int to ease the implementation. You can read the history of the bool data type in PEP 285 at https://www.python.org/dev/peps/pep-0285/.
Incidentally, True and False were only made keywords in Python 3. This means that in Python 2, it was possible to use True and False as variable names, leading to seemingly paradoxical code like this:
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.
>>> True is False
False
>>> True = False
>>> True is False
File "<ipython-input-16-780a3ed4d550>", line 1
True = False
^
SyntaxError: cannot assign to True
Fortunately, this sort of confusing code isn’t possible in Python 3, which will raise a syntax error if you try to use the keywords True or False as vari- able names.