Chapter 11: Phrases
11.8. Otherwise

We often need code which does one thing in one circumstance, and another the rest of the time. We could do this like so:

if N is 2:
    ...
if N is not 2:
    ...

but this is not very elegant, and besides, what if the action we take when N is 2 changes N so that it becomes something else?

Instead we use "otherwise":

if N is 2:
    ...
otherwise:
    ...

When there is only a single phrase we can use the shortened form:

if N is 2 then say "Hooray, N is 2!";
otherwise say "Boo, N is not 2..."

Often, though, what we want is to divide up a situation into many cases, and for this the abbreviation "otherwise if" is allowed:

if N is 1 begin:
    ...
otherwise if N is 2:
    ...;
otherwise if N is greater than 4:
    ...;

At most one of the "..." clauses is ever reached - the first which works out.

If the chain of conditions being tried consists of checking the same value over and over, we can use a convenient abbreviated form:

if N is:
    -- 1: say "1.";
    -- 2: say "2.";
    -- otherwise: say "Else.";
if the dangerous item is:
    -- the electric hairbrush:
        say "Mind your head.";
    -- the silver spoon:
        say "Steer clear of the cutlery drawer."

This abbreviated layout is not allowed to use "begin" and "end": it would look too messy, and would scarcely be an abbreviation. It is also not allowed to use "unless" instead of "if", because the result would be too tangled to follow.

(In almost every computer programming language, the word "else" is used rather than "otherwise": for the sake of familiarity, "else" can also be used here. All the same, "otherwise" seems closer to natural English.)


172
* Example  Numberless
A simple exercise in printing the names of random numbers, comparing the use of "otherwise if...", a switch statement, or a table-based alternative.

RB


PreviousContentsNext