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:
6.3.1. Comparison Operators¶
Beyond arithmetic, Python allows us to compare numbers. For instance:
3 < 6
5 > 7
3 == 3
The result of these expressions isn’t a string, it is a
type(3 < 6)
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
!=: Not equal
Notice that the equal comparison operator distinguishes itself from the assignment operator by using two equal signs.
2 == 2
3 == 3.0
1 == 0
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
It turns out that we can use comparison operators on many different types of objects! For example, we can use the
!= to check if any objects are equal in value.
'Ronaldo' == 'Waldo'
True != False
round == round
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"
'Zzyzx' < 'Yosemite'
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"
Lots of objects can be compared using comparison operators,
!=, which will return a boolean value.