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.

The middle is not optional; it is always there.
raw = input("How old are you? ")
print(raw + raw)
age = int(raw)
print(age + age)
The stageWhat is in hand
Arrived from outsideText, always
After conversionThe 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

  1. Both values are text.
  2. The type decides what the operation does.
  3. On text, adding is joining.
  4. There is no error, and there is a wrong result.

Example 2 — checking before using

  1. Print what arrived.
  2. Print its type too.
  3. If it is text — the conversion is missing.
  4. The check costs one line.
The type decides what the operation does: before the conversion adding joins, after it adding sums.