成人论坛

Implementation: Computational constructsLogical constructs and operators

Programs use computational constructs such as loops and predefined functions to break programs up into sections. This makes programs more compact, easier to write and easier to maintain.

Part of Computing ScienceSoftware design and development

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.

OperatorExplanationExample
<
Less than
age < 18
>
More than
age > 18
Less than or equal to (sometimes shown as <=)
age 鈮 18
More than or equal to (sometimes shown as >=)
age 鈮 18
=
Equality
age = 18
Inequality/Not equal to
age 鈮 18
Operator
<
ExplanationLess than
Example
age < 18
Operator
>
ExplanationMore than
Example
age > 18
Operator
ExplanationLess than or equal to (sometimes shown as <=)
Example
age 鈮 18
Operator
ExplanationMore than or equal to (sometimes shown as >=)
Example
age 鈮 18
Operator
=
ExplanationEquality
Example
age = 18
Operator
ExplanationInequality/Not equal to
Example
age 鈮 18

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 > 18OR 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.

OperatorExplanationExample
AND
The whole two or more conditions at the same time
 age > 16 AND drivingTest = 鈥淧assed鈥
OR
Used to compare two or more conditions separately
 age > 
NOT
Used to get the opposite of a condition
age 鈮 18
Operator
AND
ExplanationThe whole two or more conditions at the same time
Example
 age > 16 AND drivingTest = 鈥淧assed鈥
Operator
OR
ExplanationUsed to compare two or more conditions separately
Example
 age > 
Operator
NOT
ExplanationUsed to get the opposite of a condition
Example
age 鈮 18