Logical Operators
In This Lesson, You Will Learn:
- The three most common logical operators: And, Or and Not.
- How to use a logical operator to combine statements within an expression.
- The precedence of logical operators.
We’ve already discussed comparison operators, which take two operands and return a value of True or False depending on whether or not the operands satisfy the statement. But what if we want to create more complex expressions? Not everything in the real world is black and white, and you may wish to introduce further conditional logic, build exceptions into your rules, and make your expression code flexible, adaptable and well-rounded.
Most people would not walk into a car dealership, say “I would like to buy a blue car” and expect to drive their dream vehicle home without stating any further preferences. It would be far more realistic to say the following:
“I would like to buy a blue Ford OR Nissan that has air conditioning AND power steering.”
The capitalisation of OR and AND was done for a reason, and that is to indicate the usage of two of the most common Logical Operators.
Logical operators join together other logical statements (in other words, logical units equating to True or False) and, depending on the type of operator used, return a single Boolean logic state.
Operator | Symbol | Description | Example | Result |
---|---|---|---|---|
And | & | If both operands are True, returns True | 1 < 2 And 3 < 4 | True |
Or | | | If either or both operands are True, returns True | 1 < 2 Or 3 < 4 | True |
Not | ! | Negates the Boolean State of whatever it is attached to | Not (1 < 2) | False |
<< Previous: Lesson Summary | Next: And ( & ) >>