Mixing Boolean and Comparison Operators
As we studied the Comparison Operators and Boolean Values in the recent units, it's time to introduce a kind of operators that can be applied on Boolean values as well, the Boolean Operators. They are used to compare Boolean values. The types of operators are and
, or
and not
.
Binary Boolean Operators
and
and or
are binary Boolean operators. That means they operate on two values, the evaluated values need to be either True
or False
.
The and
operator evaluates an expression to be True
if both Boolean values are True; otherwise, it evaluates to False
.
>>> True and False
False
>>> True and True
True
A truth table shows every possible result of a Boolean operator.
Truth table for and
operator:
Expression | Evaluates to |
---|---|
True and True |
True |
True and False |
False |
False and True |
False |
False and False |
False |
The or
operator is quite interesting. The or
operator evaluates an expression to True
if either of the two Boolean values is True. If both are False, it evaluates to False.
>>> True or False
True
>>> False or False
False
Truth table for or
operator:
Expression | Evaluates to |
---|---|
True or True |
True |
True or False |
True |
False or True |
True |
False or False |
False |
NOT Operator
Unlike the other two operators, not
operator simply evaluates the opposite Boolean value. not
is a unary operator which means it operates on one value only.
Truth table for not
operator:
Expression | Evaluates to |
---|---|
not True |
False |
not False |
True |
Boolean and Comparison Operators
Now that you have a basic understanding of what's going on here, lets move to the main topic. To put this in a nutshell, since the comparison operators evaluate to Boolean values, you can use them in expressions with the Boolean operators. To break it down further, recall that the and
, or
, and not
operators are called Boolean operators because they always operate on the Boolean values True
and False
. While expressions like 4 < 5
aren’t Boolean values, they are expressions that evaluate down to Boolean values.
The computer will evaluate the left expression first, and then it will evaluate the right expression. When it knows the Boolean value for each, it will then evaluate the whole expression down to one Boolean value. You can refer to the examples for this purpose.
Here are some examples:
>>> (3 < 5) and (5 < 8)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 3) or (2 == 2)
True
You can also use multiple Boolean operators in an expression, along with the comparison operators. 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
evaluates to True
.