Logical expressions
The loop exit condition is a Boolean expression. In addition, logical expressions play a major role in branches, which will be discussed later. To compile Boolean expressions, use the comparison operators and Boolean operations listed in the following table.
Comparison operators | Logical operations | ||
More (or equal) | a>b (a>=b) | Logical "And" | And |
Less than (or equal to) | a<b (a<=b) | Logical "Or" | Or |
Equal (not equal) | a=b (a<>b) | Logical "Negation" | Not |
The result of the calculation of logical expressions is the logical constants: True and False.
Example. What is greater than epi or pie?
To find out, the easiest way is to type the following:
Calculation result: True, that is, the first expression is greater than the second.
Logical expressions can be combined using logical operations. Let X and Y be logical expressions.
- X And Y is True if and only if both expressions are True. For example, the expression x>0 And x<1 means that x belongs to the interval (0, 1).
- X Or Y is True if and only if at least one of the expressions is True. For example, the expression x<0 Or x>1 means that x does not belong to the interval [0, 1].
- Not X is true if and only if X is false. For example, Not x>0 means x<=0.
Tip. In order to remember these rules, we denote the Truth through 1, and false — through 0, which is the standard in programming. Then And coincides with the usual multiplication, and therefore this operation is called logical multiplication. Similarly, Or is called logical addition, since for 0 and 1 it coincides with the addition of numbers (with the easily remembered exception: 1+1 = 1).
Rule 4. There should be spaces in the formulas around logical operators.
Example. Players Sam and John in each round randomly either get a point or get nothing. Who will score 10 points first?
John = 0
do
Sam = Sam + random(1)
John = John + random(1)
until(Sam = 10 Or John = 10)
Recall that the random (1) function returns 0 or 1 with equal probabilities. The condition for exiting the cycle is that at least one of the players scorule 10 points.