Logical Operators
Last updated
Was this helpful?
Last updated
Was this helpful?
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.
Imagine that there are three different stacks of sandwiches as follows:
Peanut Butter and Jelly
Peanut Butter or Jelly
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 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:
If you ever run into problems with arithmetic operators, here is a handy cheat sheet!