Comparison and Boolean Operators
Programming gets interesting when we add the ability to test different conditions and change the behavior of a program based on the result. Conditional and Boolean operations allow us to do this. In previous lessons, we’ve already touched on Boolean data types as well as simple conditional statements. Here we will go into a little more detail.
Boolean values and expressions; comparison operators
In python, there are two Boolean values: True and False:
[1]:
print(type(True))
<class 'bool'>
and yes, the first letter must be capitalized. We can use boolean expressions to make a test or compare two values. The result of a boolean expression is either True or False. For example,
[2]:
a = 8
b = 3
print(a == b)
False
[3]:
print(a+b == 11)
True
[4]:
print(a-b < 6)
True
As demonstrated above, a boolean expression must consist of 2 or more values to be compared along with a comparison operator. There are six common comparison operators, most of which are intuitive.
Operator |
Description |
Example |
|---|---|---|
== |
Equal to |
a == b |
!= |
Not equal to |
a != b |
< |
Less than |
a < b |
> |
Greater than |
a > b |
<= |
Less than or equal to |
a <= b |
>= |
Greater than or equal to |
a >= b |
Why two symbols when performing an equal to comparison? Because = is already being used as an assignment operator, e.g. a = 10 assigns the value 10 to the variable a.
Logical operators
In addition to comparing two or more values to one another when performing a test, we might want to perform multiple comparisons simultaneously. This can be done using one of python’s three logical operators: and, or, and not. These mean essentially the same thing in python as they do in English. For example:
[5]:
print(a == 8 and b == 3)
True
Here we have a boolean expression where two comparisons are made. The expression evaluates to True only if both a is equal to 8 and b is equal to 3. Another example:
[6]:
print(a+b > 15 and b < 5)
False
While b is less than 5, a+b is not greater than 15, so this evaluates to False.
Where the and operator will only evaluate to True if all comparisons are individually true, the or operator will evaluate to True if any of the individual comparisons are individually true:
[7]:
print(a+b > 15 or b < 5)
True
Finally, the not operator evaluates to True when the result of a boolean expression is False. In other words, it flips the expected result of a boolean expression:
[8]:
print(not a == 8)
False