Until now your programs were movies — they played the same every time. input() makes them games.
The book’s take on input() and int(). The conversion part is the one that bites people — watch for it. Enrolled in our Runestone course? Open it from there so your progress counts.
Still in Programs, and about to close a loop back to Bits. Today’s gotcha is really a Unit 1 idea in disguise: the number 5 and the character “5” are stored as different bit patterns.
Nothing is broken. The machine did exactly what the
code said — it just thought those were pieces of text, not numbers, because
everything typed into input() arrives as text. Today you learn the
one-word fix, and why the bug happens in the first place. This is probably the single most common
beginner bug there is.
Output you already have: print shows a value.
Input is the mirror image: input() pauses the program, waits for the
user to type, and hands back whatever they typed. You store it in a variable, exactly like before:
name = input("Your name? ") print("Hi, " + name)
name ← INPUT() DISPLAY("Hi, " + name)
Here is the trap. Whatever the user types — even
42 — comes back as a string (text). Text plus text
doesn’t add, it joins. So to do math on a typed number, you must first
convert it with int() (whole numbers) or float()
(decimals):
age = input("Age? ") age = int(age) # text -> number next_age = age + 1
# age holds "17" (text) # now age holds 17 (a number) # 17 + 1 = 18, real math
Hover or tap a line to light its twin. Skip line 2 and
age + 1 crashes — you can’t add a number to text.
int() or float() first. This is the fix for the hook, and for about
a third of the bugs you’ll write this month.
"5" different from 5? Because
they’re different bits. The character “5” is stored as its ASCII code
(00110101); the number 5 is stored as the binary value
(00000101). Same symbol on screen, different patterns underneath — which is
exactly why the machine won’t add them until you convert.
Type two numbers, then run the program without the conversion and with it. Same inputs, very different answers.
input() collects it; the exam writes INPUT.print / DISPLAY
shows on screen.int()
or float(). Required before doing math on typed input.Five questions. Pick an answer for instant feedback.
The moment a program accepts input(), it stops being
fully under your control — a user, who might be careless or hostile, now feeds it values.
They’ll type letters where you wanted a number, leave a box blank, paste a thousand
characters. A program that assumes input is always well-formed is a program waiting to crash, and
sometimes waiting to be attacked.
This is why professionals treat all input as suspect until checked — a habit called input validation that you’ll practice at the end of this unit (2.16) and that becomes a security issue in Unit 7. Today’s lesson is the gentle first version: a typed “5” isn’t a number until you make it one.