Grade 8 Computer Science · Input, output and files
Input always arrives as text
Why conversion is a separate step, and why it is forgotten so often.
Seven plus seven equals seventy-seven
A program asks the user how old they are, receives 7, and adds the answer to itself. It does not stop or complain, and prints 77. The computer did not get the arithmetic wrong, so what exactly did it receive from the keyboard?
Until here all the data was written in the code itself. A useful program receives data from outside — from the user, from a file, from a network — and the moment it does, one rule enters that surprises nearly everyone the first time.
raw = input("How old are you? ")
print(raw + raw)
age = int(raw)
print(age + age)| The stage | What is in hand |
|---|---|
| Arrived from outside | Text, always |
| After conversion | The type you asked for |
The bug that looks innocent
The classic mistake is to forget the conversion and then to add. The result is not an error but a join — two single-digit inputs give a two-character text that looks like a large number. The program carries on happily, and that number rolls onwards and contaminates every computation that touches it. This is a clear logic bug in the terms of the unit on bugs: everything is legal, everything runs, and the answer is quietly wrong. The quick check that catches it is to print what arrived and its type before using it.
Example 1 — why adding without converting joins
- Both values are text.
- The type decides what the operation does.
- On text, adding is joining.
- There is no error, and there is a wrong result.
Example 2 — checking before using
- Print what arrived.
- Print its type too.
- If it is text — the conversion is missing.
- The check costs one line.