Booleans
Contents
5.3. Booleans¶
In this short section, we’ll see how to ask Python to compare things and discover that Python’s answer is of a new type: bool
.
5.3.1. Comparison Operators¶
Beyond arithmetic, Python allows us to compare numbers. For instance:
3 < 6
True
5 > 7
False
3 == 3
True
The result of these expressions isn’t a string, it is a bool
:
type(3 < 6)
bool
A Boolean (named after George Boole) is a logical data type, indicating whether something is True or False. Boolean values result when we use comparison operators to compare the value of two expressions.
The standard set of comparisons operators carries over from math,
<
: Less than<=
: Less or equal>
: Greater than>=
: Greater or equal==
: Equal!=
: Not equal
Notice that the equal comparison operator distinguishes itself from the assignment operator by using two equal signs.
2 == 2
True
3 == 3.0
True
1 == 0
False
Any expressions to the left or right of the comparison operator will be evaluated before the comparison is carried out.
(3 * 4) / 6 < 1 + 2 + 3 + 4
True
It turns out that we can use comparison operators on many different types of objects! For example, we can use the ==
and !=
to check if any objects are equal in value.
'Ronaldo' == 'Waldo'
False
True != False
True
round == round
True
And many objects support greater than/less than comparison too. For instance, a string is less than or greater than another string based on alphabetical order.
"Avocado" < "Banana"
True
'Zzyzx' < 'Yosemite'
False
Notice that if you look at a dictionary, words like “Fire” will show up before “Fireplace” – the same holds true with string comparisons in Python.
"Fire" < "Fireplace"
True
5.3.2. Summary¶
Lots of objects can be compared using comparison operators,
<
<=
>
>=
==
!=
, which will return a boolean value.