Logical Operators

Boolean Operators

Operations like addition and subtraction return a number when applied to mathematical expressions - in a similar way, boolean operators return either true or false when applied. They are useful in setting conditions to perform certain operations (as we will see later in this chapter). We will focus on three main boolean logical operators: AND, OR and NOT.

Logical Operators: AND, OR and NOT

Imagine that there are three different stacks of sandwiches as follows:

  1. Peanut Butter and Jelly

  2. Peanut Butter or Jelly

  3. Peanut Butter, not Jelly

This means that if you pick a sandwich from Stack 1, it will contain both Peanut Butter and Jelly. If you pick it from Stack 2, depending on the sandwich it can contain either only Peanut Butter or only Jelly. The last stack has only Peanut Butter sandwiches - no sandwiches in this stack have Jelly.

Boolean operators work in the exact same way. The diagram below helps demonstrate how we can use these operators to look for the sandwich we want.

Arithmetic Operators: Greater than, less than, equal to

Arithmetic Operators are straightforward. In fact, you might have already seen them in mathematics. They are used to compare values rather than statements. For example, is 2 greater than 3? The answer is obviously false. In Python we can evaluate these statements in the following ways:

>>>print(2>=3) 
False
>>>print(3>=2)
True
>>>print((4*5) < (2*3))
False
>>>print(4==4) 
True 
>>>print("b">"a")
True

If you ever run into problems with arithmetic operators, here is a handy cheat sheet!

Last updated