2.2. Booleans#
Amanda R. Kube Jotte, Dan L. Nicolae, and Evelyn Campbell
Booleans are a data type with only two possible values: True
or False
. Because they have two outcomes, we also call them binary. In Python, Booleans can act like numbers, where True
is treated as 1
and False
as 0
. This means they can be used not only in logic but also in calculations.
Booleans are most often created by using comparison operators, which check whether a relationship between values is true or false. Let’s start by learning how to do comparisons in Python.
Comparison operators#
Comparison operators are used to compare values using mathematical logic and return a single Boolean value of either True
or False
. We will see later in this book that they are important for counting, extracting and modifying data. For example, counting the number of students with GPA higher than a given threshold requires a comparison, for each student, of their GPA to the threshold.
In the cell below, Python compares two integers (is five strictly smaller than seven?) and returns the Boolean that reflects the comparison.
5 < 7 # This is an expression, specifically a boolean expression, which can be answered with True or False
True
In the expression above, Python followed mathematical logic and declared the comparison to be true.
Below is a table of comparison operators.
Operator |
What it means |
---|---|
== |
Equal |
!= |
Not equal |
< |
Less than |
<= |
Less or equal |
> |
Greater than |
>= |
Greater or equal |
To better understand how these operators work, we illustrate their use in the cell below where we compare two real numbers.
# Recall that the print function displays information.
# Below it will display some text and then the result of a comparison.
# You will learn more about text like this later in this chapter.
print("1.5 == 0.8:", 1.5 == 0.8)
print("1.5 != 0.8:", 1.5 != 0.8)
print("1.5 < 0.8:", 1.5 < 0.8)
print("1.5 <= 0.8:", 1.5 <= 0.8)
print("1.5 > 0.8:", 1.5 > 0.8)
print("1.5 >= 0.8:", 1.5 >= 0.8)
1.5 == 0.8: False
1.5 != 0.8: True
1.5 < 0.8: False
1.5 <= 0.8: False
1.5 > 0.8: True
1.5 >= 0.8: True
Warning
Be careful when comparing floats. Because of the way computers store decimal values, calculations may not be exact. For example, the code below will give the result False
.
0.1 + 0.2 == 0.3 # False
Even though mathematically 0.1 + 0.2 equals 0.3, the computer stores the result as something very close to, but not exactly, 0.3.
Instead of checking floats for exact equality, check whether they are close enough within a small tolerance (such as plus or minus 1e-9). This way, small rounding differences won’t cause your comparisons to fail.
For example:
-1e-9 < (0.1 + 0.2) - 0.3) < 1e-9 # True
Note
The e
above is how Python displays scientific notation. So, 1e-9
means \(1 \times 10^{-9}\).
If you want to explore this further, try adding 0.1 + 0.2 in your own Python session.
Logical (Boolean) operators#
Python’s logical operators perform Boolean arithmetic on one or two inputs and return either True
or False
. The table below shows three logical operators.
Operator |
What it means |
Examples (that return True) |
---|---|---|
and |
True if both are true |
(7 > 5) and (1.2 != 1.3) |
or |
True if at least one is true |
(7 < 5) or (1.2 != 1.3) |
not |
True if input is false |
not (7 == 5) |
print(not (7 == 5))
print(not (7 > 5))
print(not (1.2 != 1.3))
print((7 > 5) and (1.2 != 1.3))
print((7 > 5) & (1.2 != 1.3))
print((7 < 5) or (1.2 != 1.3))
print((7 < 5) | (1.2 != 1.3))
True
False
False
True
True
True
True
Note
You will see in some code examples here and elsewhere the logical operators and
and or
replaced by something called bitwise operators: &
used instead of and
and |
instead of or
. Bitwise operators work at the level of bits (binary representation of integers). Note that, even if they give the same results when applied to Boolean data types (as in the examples above), they have different meanings for other data types.
As a rule of thumb, you should use and
and or
for most conditionals that you write. Later in this book, we will introduce data types that can include multiple elements (ie data types that hold multiple pieces of data inside them). When you want to write a conditional to check these individual elements you will use &
and |
instead of and
and or
.
Finally, an expression can contain multiple comparisons, and all comparisons must hold in order for the whole expression to be True. You can see a couple of examples below. In the first, Python evaluates first the expression 5 - 2
(equal to 3
), then evaluates 1.2 <= 1.8
and 1.8 < 3
(both True), and finally use the Boolean operator and
to evaluate the full expression.
1.2 <= 1.8 < 5 - 2
True
The expression above is essentially a shorthand for the following expression. Notice that they produce the same result.
1.2 <= 1.8 and 1.8 < (5-2)
True
Truth tables#
An easy way to summarize the outcome of logic operators are truth tables, and we show them below for and
and or
. Note that we used them in the multiple comparisons above. They are useful for algorithmic thinking in programming. For simplicity we summarize them in a single table.
a |
b |
a and b |
a or b |
---|---|---|---|
True |
True |
True |
True |
True |
False |
False |
True |
False |
True |
False |
True |
False |
False |
False |
False |
Boolean Arithmetic and Order of Operations#
Below, we consider the expression 5 < 3
, which reads “5 is less than 3.”
5 < 3
False
Because 5 is not in fact less than 3, the entire statement is False
, thus this expression evaluates to False
.
Recall that False
has a numerical value of 0, so we can perform mathematical operations on Booleans. Evaluating 5 < 3
first and then adding 5 is the same as 0 + 5, as shown below.
(5 < 3) + 5
5
Note
There is a default order of operations when we include comparisons. We provide a summary table showing this ordering below, some of which (namely operators included in precedence numbers 3, 6, 7, and 8) is outside the focus of this textbook.
Precedence |
Operators |
Example |
---|---|---|
1 |
|
|
2 |
|
|
3 |
|
|
4 |
|
|
5 |
|
|
6 |
|
|
7 |
|
|
8 |
|
|
9 |
Comparisons: |
|
10 |
|
|
11 |
|
|
12 |
|
|
As is common with long mathematical expressions, it is often useful to explicitly impose an ordering by using parentheses.
We can combine expressions in further comparisons. We see that (5 < 3) is less than 10, and thus returns another Boolean value of True
:
(5 < 3) < 10
True
The bool()
function converts an input (i.e. a numeric value, or, we will see later, a string, or even data structure) to a boolean value.
bool(5)
True
Any input that has value, contains an element, or is nonzero will give an output of True
when passed into the bool()
function. Any input that is null, empty, or zero will give a False
output.
print(bool(6542))
print(bool(0))
True
False
We can also convert boolean data types to integers and floats
print(int(False))
print(float(True))
0
1.0
Now that we can build mathematical and boolean expressions (ie a series of mathematical and/or boolean operations on data), it can be useful to save the results of those expressions in case we want to revisit them later. In the next section, we will learn how to store the result of any expression or function in a variable using assignment.