As we saw, comparison operators allow us to examine the relationship of two values. But what if we’re looking at more than two values?
Logical operators, also known as boolean operators, evaluate multiple boolean expressions. Rather than determining if one relationship is true or false, it looks at several relationships by connecting them with logical operators and then determining the logic/validity of the overall expression.
Logical operators include:
((4 > 1) AND (2 < 7))is the same as
(TRUE AND TRUE). Evaluates to true.
((8 > 6) OR (3 > 6))is the same as
(TRUE OR FALSE). Evaluates to true.
NOT (1 < 3)evaluates to
NOT (TRUE). Evaluates to false.
The examples given are only a few of the outcomes that you can reach using logical operators. Using logical operators and boolean expressions enable us to handle different scenarios in our program. For example, what if we only had apples in our fridge? If a recipe asked for either apples OR pears, we could still make the recipe. But if a recipe requires both apples AND pears, we wouldn’t be able to make it.
Take a look at these following recipes and determine if you can make them with the fruit on hand:
How do boolean operators allow us to make our programs more flexible or more strict? Can we start to see ways we can write programs that can handle different scenarios?