Skip to content

One or the Other

Two paths from one question: do this, or else do that. And a chain of questions when there are more than two answers.

Unit 1 left the guessing game with three separate tests:

IF guess < 7 THEN SHOW "Too low"
IF guess > 7 THEN SHOW "Too high"
IF guess = 7 THEN SHOW "Correct!"

The computer runs all three, every time. It asks whether the guess is low, then whether it is high, then whether it is right. Only one of them can be true, but nothing in the program says so. Those three questions do not know about each other.

Do this, or else do that

ELSE gives one question two paths.

ASK "Guess my number? " INTO guess
IF guess = 7 THEN
  SHOW "Correct!"
ELSE
  SHOW "Not this time"
END
Output
Guess my number? 4
Not this time

Read it aloud and it says what it does: if the guess is seven, show Correct!, or else show Not this time. Exactly one of those two lines runs. Never both, and never neither.

The END marks where the decision finishes and the program carries on.

More than two answers

A guess can be low, high or right. That is three answers, not two. Hang another question off the ELSE:

ASK "Guess my number? " INTO guess
IF guess < 7 THEN
  SHOW "Too low"
ELSE IF guess > 7 THEN
  SHOW "Too high"
ELSE
  SHOW "Correct!"
END
Output
Guess my number? 4
Too low

The computer works down the chain and stops at the first question that comes back yes. A low guess shows Too low and skips the rest. Otherwise it tries the next question. The last ELSE catches everything left over, which here is the one case where a guess is neither low nor high.

Compare that with the three separate tests at the top of this unit. Same three messages, but the chain says something the separate tests only implied: these are three answers to one question, and exactly one of them happens.

When it’s wrong, see why

  • Two messages appear. You have separate IFs where you wanted a chain. Each IF asks its own question, so more than one can come back yes.
  • Nothing appears at all. No question came back yes, and there is no last ELSE to catch the rest. Add one, even if it only says that nothing matched.
  • The wrong branch runs for a value on the boundary. Check which test claims the edge. guess < 7 and guess > 7 both leave 7 out, which is what lets the last ELSE catch it.

What you’ve learnt

  • ELSE gives a question a second path, and exactly one path always runs.
  • ELSE IF chains more questions on, and the computer stops at the first yes.
  • A last ELSE catches everything the questions above it did not.
  • A chain says that these answers belong to one question. Separate IFs do not.

What’s next

Every question so far is answered and forgotten in the same breath. In Unit 3 you keep the answer, which turns out to be how a game knows it is over.