Conditionals
Information, while necessary, is not sufficient for logic
So far our programs have run every line, in order, every time. Conditionals let a program make decisions. With a conditional, a block of code only runs when a certain condition is met. This is where booleans become useful.
- Conditional (noun)
- A section of code that only executes if a certain condition is true
Comparing Values
Conditions are usually made by comparing two values. A comparison asks a question, and
the answer is always a boolean: true or false.
| operator | meaning | shorthand |
|---|---|---|
= | equal to | = |
≠ | not equal to | != |
> | greater than | > |
< | less than | < |
≥ | greater than or equal to | <= |
≤ | less than or equal to | >= |
In order to type these characters in the CSP editor you may use the buttons at the top of the editor or the auto complete shorthands.
Arithmetic is evaluated first, and then the comparison is made. The last line is a handy way to check whether a number is even.
The single equals sign
=asks a question: “are these two values equal?” It does not store anything. To store a value in a variable, use the assignment arrow←.
Comparisons can be combined with AND, OR, and NOT, just like any other boolean.
IF
An IF statement runs a block of code only when its condition is true. The condition
goes inside parentheses, and the code to run goes inside curly braces.
Because temperature ≥ 80 is true, the message is displayed. If we change
temperature to 10, the condition is false, the block is skipped, and nothing is
displayed.
Any expression that results in a boolean can be used as a condition, including a variable that holds a boolean.
ELSE
Often we want to do one thing when a condition is true and something different when it
is false. We can add an ELSE block after an IF block. Exactly one of the two blocks
will run, never both and never neither.
Since 7 MOD 2 is 1, the condition is false and the ELSE block runs.
An ELSE block can only come directly after an IF block, and it has no condition of
its own. It simply means “otherwise.”
Choosing Between Many Options
CSP has no ELIF or match statement. When there are more than two options, we place
another IF inside of an ELSE.
The conditions are checked from top to bottom, and as soon as one is true the rest are
skipped. Here score ≥ 90 is false, so we move to the ELSE. Then score ≥ 80 is
true, so B is displayed.
Order matters. If we checked score ≥ 80 first, a score of 95 would display B
instead of A, because that condition would be met before we ever reached the check for
90.
Sometimes combining conditions with AND and OR is cleaner than nesting.
Almost every programming language has conditionals, though many add extra forms like
else iforswitch. The idea of conditional statements is the same everywhere: run some code only when a condition is met.
Next: Case Sensitivity