Logical constructs and operators
The previous program checked to see if the age value was above or below a certain value. We can use logical constructs to do this.
Operator | Explanation | Example |
| Less than |
|
| More than |
|
| Less than or equal to (sometimes shown as <=) |
|
| More than or equal to (sometimes shown as >=) |
|
| Equality |
|
| Inequality/Not equal to |
|
Operator |
|
---|---|
Explanation | Less than |
Example |
|
Operator |
|
---|---|
Explanation | More than |
Example |
|
Operator |
|
---|---|
Explanation | Less than or equal to (sometimes shown as <=) |
Example |
|
Operator |
|
---|---|
Explanation | More than or equal to (sometimes shown as >=) |
Example |
|
Operator |
|
---|---|
Explanation | Equality |
Example |
|
Operator |
|
---|---|
Explanation | Inequality/Not equal to |
Example |
|
Using logical constructs means you can check if a variable contains a value that meets, or doesn't meet, a certain condition. They are very useful when you are using conditional statements, such as IF statements.
On the other hand, logical operators are used when we want to include two or more parts of a condition (and also the opposite of a condition). There are three logical operators AND, OR and NOT. You can often see these easily as they are written in block capital letters. Below are some examples of these operators being used.
It is best to think of these logical operators as a set of conditions.
When using the AND operator, all parts of the condition must be true before the whole condition will return as true. For example, IF age > 18
AND testPassed = 鈥淭rue鈥, then both age must be 17 or lower AND testPassed must also be True.
When using the OR operator only one of the conditions must be true for the whole condition to return as true. Eg. If age > 18
OR testPassed = 鈥淭rue鈥, if either age is 17 or lower OR if testPassed is True, then the whole condition will return as true.
When using the NOT operator the opposite of the condition will return as true. Eg IF age > 18
any number 18 or greater will return as true.
Operator | Explanation | Example |
| The whole two or more conditions at the same time |
|
| Used to compare two or more conditions separately |
|
| Used to get the opposite of a condition |
|
Operator |
|
---|---|
Explanation | The whole two or more conditions at the same time |
Example |
|
Operator |
|
---|---|
Explanation | Used to compare two or more conditions separately |
Example |
|
Operator |
|
---|---|
Explanation | Used to get the opposite of a condition |
Example |
|