The Python Boolean type is one of Python’s built-in data types. It’s used to represent the truth value of an expression. For example, the expression 1 <= 2 is True, while the expression 0 == 1 is False. Understanding how Python Boolean values behave is important to programming well in Python.
In this tutorial, you’ll learn how to:
- Manipulate Boolean values with Boolean operators
- Convert Booleans to other types
- Convert other types to Python Booleans
- Use Python Booleans to write efficient and readable Python code
Free Bonus: 5 Thoughts On Python Mastery, a free course for Python developers that shows you the roadmap and the mindset you’ll need to take your Python skills to the next level.
The Python Boolean Type
The Python Boolean type has only two possible values:
TrueFalse
No other value will have bool as its type. You can check the type of True and False with the built-in type():
>>> type(False)
<class 'bool'>
>>> type(True)
<class 'bool'>
The type() of both False and True is bool.
The type bool is built in, meaning it’s always available in Python and doesn’t need to be imported. However, the name itself isn’t a keyword in the language. While the following is considered bad style, it’s possible to assign to the name bool:
>>> bool
<class 'bool'>
>>> bool = "this is not a type"
>>> bool
'this is not a type'
Although technically possible, to avoid confusion it’s highly recommended that you don’t assign a different value to bool.
Python Booleans as Keywords
Built-in names aren’t keywords. As far as the Python language is concerned, they’re regular variables. If you assign to them, then you’ll override the built-in value.
In contrast, the names True and False are not built-ins. They’re keywords. Unlike many other Python keywords, True and False are Python expressions. Since they’re expressions, they can be used wherever other expressions, like 1 + 1, can be used.
It’s possible to assign a Boolean value to variables, but it’s not possible to assign a value to True:
>>> a_true_alias = True
>>> a_true_alias
True
>>> True = 5
File "<stdin>", line 1
SyntaxError: cannot assign to True
Because True is a keyword, you can’t assign a value to it. The same rule applies to False:
>>> False = 5
File "<stdin>", line 1
SyntaxError: cannot assign to False
You can’t assign to False because it’s a keyword in Python. In this way, True and False behave like other numeric constants. For example, you can pass 1.5 to functions or assign it to variables. However, it’s impossible to assign a value to 1.5. The statement 1.5 = 5 is not valid Python. Both 1.5 = 5 and False = 5 are invalid Python code and will raise a SyntaxError when parsed.
Python Booleans as Numbers
Booleans are considered a numeric type in Python. This means they’re numbers for all intents and purposes. In other words, you can apply arithmetic operations to Booleans, and you can also compare them to numbers:
>>> True == 1
True
>>> False == 0
True
>>> True + (False / True)
1.0
There aren’t many uses for the numerical nature of Boolean values, but there’s one technique you may find helpful. Because True is equal to 1 and False is equal to 0, adding Booleans together is a quick way to count the number of True values. This can come in handy when you need to count the number of items that satisfy a condition.
For example, if you want to analyze a verse in a classic children’s poem to see what fraction of lines contain the word "the", then the fact that True is equal to 1 and False is equal to 0 can come in quite handy:
>>> lines="""\
... He took his vorpal sword in hand;
... Long time the manxome foe he sought—
... So rested he by the Tumtum tree
... And stood awhile in thought.
... """.splitlines()
>>> sum("the" in line.lower() for line in lines) / len(lines)
0.5
Summing all values in a generator expression like this lets you know how many times True appears in the generator. The number of times True is in the generator is equal to the number of lines that contain the word "the", in a case-insensitive way. Dividing this number by the total number of lines gives you the ratio of matching lines to total lines.
To see why this works, you can break the above code into smaller parts:
>>> lines = """\
... He took his vorpal sword in hand;
... Long time the manxome foe he sought—
... So rested he by the Tumtum tree
... And stood awhile in thought.
... """
>>> line_list = lines.splitlines()
>>> "the" in line_list[0]
False
>>> "the" in line_list[1]
True
>>> 0 + False + True # Equivalent to 0 + 0 + 1
1
>>> ["the" in line for line in line_list]
[False, True, True, False]
>>> False + True + True + False
2
>>> len(line_list)
4
>>> 2/4
0.5
The line_list variable holds a list of lines. The first line doesn’t have the word "the" in it, so "the" in line_list[0] is False. In the second line, "the" does appear, so "the" in line_list[1] is True. Since Booleans are numbers, you can add them to numbers, and 0 + False + True gives 1.
Since ["the" in line for line in line_list] is a list of four Booleans, you can add them together. When you add False + True + True + False, you get 2. Now, if you divide that result by 4, the length of the list, you get 0.5. The word "the" appears in half the lines in the selection. This is a useful way to take advantage of the fact that Booleans are numbers.
Boolean Operators
Boolean operators are those that take Boolean inputs and return Boolean results.
Note: Later, you’ll see that these operators can be given other inputs and don’t always return Boolean results. For now, all examples will use Boolean inputs and results. You’ll see how this generalizes to other values in the section on truthiness.
Since Python Boolean values have only two possible options, True or False, it’s possible to specify the operators completely in terms of the results they assign to every possible input combination. These specifications are called truth tables since they’re displayed in a table.
As you’ll see later, in some situations, knowing one input to an operator is enough to determine its value. In those cases, the other input is not evaluated. This is called short-circuit evaluation.
The importance of short-circuit evaluation depends on the specific case. In some cases, it might have little effect on your program. In other cases, such as when it would be computationally intensive to evaluate expressions that don’t affect the result, it provides a significant performance benefit. In the most extreme cases, the correctness of your code can hinge on the short-circuit evaluation.
Operators With No Inputs
You can think of True and False as Boolean operators that take no inputs. One of these operators always returns True, and the other always returns False.