Asking the Player
Until now you filled the boxes when you wrote the program. Now the program asks whoever is using it — and starts doing something different depending on the answer.
So far, you decided what went in every box — back when you wrote the program. That means the program does the same thing every single time it runs. A real program does something more interesting: it asks the person using it, and puts their answer in a box. That is the moment a program stops reciting and starts responding.
Read an answer into a box
The instruction we want is "ask a question, wait for the person to type something, and keep their answer." In pseudocode:
ASK "What is your name? " INTO name
SHOW "Hello, ", name
In BASIC the instruction is INPUT. One catch from the last unit: the answer is text,
so its box needs a single-letter name ending in $ — we'll use n$:
10 INPUT "What is your name? "; n$
20 PRINT "Hello, "; n$
Line 10 shows the question and waits for someone to type a reply and press Enter;
whatever they type is dropped into the box n$. Line 20 then greets them by looking in
that box. Run it and type Sam:
Now run the same program again and type something else — Ada:
That is the whole point. The program didn't change between those two runs — you did. A program that asks can give a different result every time, depending on who's at the keyboard and what they say. Every game you'll build leans on this: it is how the player plays instead of just watching.
When it's wrong, see why
Variable not found, or the line won't run. You named the text box with more than one letter —name$, say. BASIC only allows single-letter names for text boxes (Unit 4), soname$is rejected. Usen$. (Other languages are happy withname; Sinclair BASIC isn't — the rules are local.)- It greets you with an empty space. You pressed Enter without typing anything, so the box holds nothing. Run it again and type a reply before Enter.
- The greeting runs into the name, like
Hello,Ada. The fixed text needs its space inside the quotes —"Hello, "— from Unit 3. The computer joins on exactly what you wrote.
What you've learnt
- Input lets a program read what someone types and keep it in a box — the program responds to its user.
- A program that asks gives a different result for a different answer, without a line of its code changing. That's the difference between watching and playing.
- The naming rules are local: BASIC needs a single-letter
$name for a text box; the idea — ask, and remember the answer — is the same in every language.
What's next
You can ask for a name and greet it. But the answer to a question is often a number — and numbers can be added, compared, counted. In Unit 6 we ask for numbers and do arithmetic with them, the first time the program works something out from what the player gave it.