Comparisons

Comparisons#

A Boolean value is a value that can only be True or False. It is called “Boolean” after the mathematician and logician George Boole

Boolean values most often arise from comparison operators. Python includes a variety of operators that compare values. For example, 3 is larger than 1:

3 > 1
True

> is the greater than comparison operator. It takes the value to the left and asks if it is greater than the value to right. The answer can only be True or False.

The value True indicates that the comparison is valid; Python has confirmed this simple fact about the relationship between 3 and 1.

Python uses the special bool type for values that can only be True or False.

type(3 > 1)
bool

Here we confirm to ourselves that 3 is greater than the result of the expression 1 + 1:

3 > 1 + 1
True

The value True indicates that the comparison is valid; Python has confirmed this simple fact about the relationship between 3 and 1+1. The full set of common comparison operators are listed below.

Comparison

Operator

True example

False Example

Less than

<

2 < 3

2 < 2

Greater than

>

3>2

3>3

Less than or equal

<=

2 <= 2

3 <= 2

Greater or equal

>=

3 >= 3

2 >= 3

Equal

==

3 == 3

3 == 2

Not equal

!=

3 != 2

2 != 2

Here are some more examples:

4 < 5
True
4 < 3
False
4 <= 4
True

Notice the == in the table above.

The double equals == is different from the single = that we saw before in assignment. Here is assignment.

a = 4

Notice it does not display a value, because it is an assignment, and not an expression.

== is different - it’s a comparison operator like < or >. It checks whether two values are equal, and returns True or False:

a == 4
True

This is an expression, because == is an operator, to say how values should be combined, like + or *.

Strings can also be compared, and their order is alphabetical. A shorter string is less than a longer string that begins with the shorter string.

"Dog" > "Catastrophe"
True
"Catastrophe" > "Cat"
True

Note

This page has content from the Comparison notebook of an older version of the UC Berkeley data science course. See the Berkeley course section of the license file.