Lesson 2 — Input
By the end of this you can: ask a question, keep the answer in a variable, turn a typed answer into a number you can do sums with, and know why that last step is not optional.
Still plain Python. Everything here runs in the playground: press Run, and when the program asks a question a box appears in the output pane for you to type into. Press Enter to answer.
Asking a question
One function does all of it:
name = input("What is your name? ")
print("Hello, " + name + "!")
What is your name? Ada
Hello, Ada!
Run that and type your own name; the second line changes to match. Three things happen on line 1, in this order:
What is your name?is printed — that is the bit in the brackets, and it is called the prompt.- The program stops and waits. Nothing below runs yet.
- What you typed is handed back, and
=puts it inname, exactly the way lesson 1 put a 0 inscore.
Leave a space at the end of the prompt, inside the quotes:
"What is your name? ". Without it you type right up against the question
mark, which looks like a mistake because it is one.
The prompt is optional. input() with empty brackets waits for a line without
asking anything, which is nearly always worse — a program that sits there
silently looks like a program that has crashed.
The answer is always text
This is the one thing in the lesson that catches everybody, so here it is going wrong:
age = input("How old are you? ")
print(age + 1)
How old are you? 12
TypeError: can only concatenate str (not "int") to str
You typed a number. You can see it on the screen. Python still says you tried
to join text — because input() always hands back a string, every time,
whatever you typed into it. 12 arrived as "12", and lesson 1 already
showed what + does to a string.
It is worth saying the rule to yourself as a sentence: input gives me text,
even when it looks like a number. The error message will not tell you that —
it talks about str and int and never mentions input at all.
Turning text into a number
int(), from the end of lesson 1:
age = input("How old are you? ")
age = int(age)
print("Next year you will be", age + 1)
How old are you? 12
Next year you will be 13
Line 2 takes the text out of age, makes a number of it, and puts the number
back under the same name. Once that line has run, age is a number and behaves
like one.
You will usually see the two lines written as one, with input inside int:
age = int(input("How old are you? "))
print("Next year you will be", age + 1)
How old are you? 12
Next year you will be 13
Read it from the inside out: input asks and gives back text, int turns that
text into a number, = stores it. Both versions are fine. Write the two-line
one until the one-liner reads easily.
For a number with a decimal point, int is the wrong tool — it wants a whole
number and nothing else. float() is the one that takes both:
temp = float(input("Temperature in Celsius? "))
print("In Fahrenheit:", temp * 9 / 5 + 32)
Temperature in Celsius? 21.5
In Fahrenheit: 70.7
When the answer is not a number
int() is strict, and a person typing at a keyboard is not:
age = int(input("How old are you? "))
print(age)
How old are you? twelve
ValueError: invalid literal for int() with base 10: 'twelve'
ValueError means the value was the wrong shape: int() was given a string,
which is what it wants, but the string was not a number. It happens with
twelve, with 12 years, with an empty answer, and — annoyingly — with
12.0, because that is not a whole number. float() would take it.
Handling that properly takes an if, which is the next lesson. For now,
knowing what the message means is enough: the program did not break, the
answer did not fit.
A program that asks more than once
Each input() is its own question, and they happen in the order they are
written:
name = input("Name? ")
coins = int(input("How many coins? "))
value = int(input("Worth each? "))
total = coins * value
print(name + " has " + str(total) + " gold")
Name? Ada
How many coins? 3
Worth each? 25
Ada has 75 gold
Both of the last lesson's habits are in there: int() on the way in, because
coins * value needs numbers, and str() on the way out, because
" has " + total needs text. Getting those two the right way round is most of
what input work is.
Now put it on the screen
An answer can decide what a game window says. Ask before the window opens:
from kaypy import *
name = input("Who is playing? ")
kaypy(width=800, height=600, background=[20, 24, 36])
add([text("Good luck, " + name, size=36), pos(40, 40)])
add([text("Press Stop when you are done.", size=20), pos(40, 110)])
Press Run, answer the question, and the window opens with your name in it.
The question arrives in a pop-up box, not in the output pane. That is not a bug and it is worth knowing why: the moment
kaypy()opens a window, the game takes the keyboard so that the arrow keys reach the game and not the page. A typing box in the output pane would collect nothing, so the browser asks in a dialog instead. In a plain program, with no window, you get the output pane.
So input() is a way to set a game up — a name, a difficulty, how many
rounds — rather than a way to play one. Playing means reacting to keys while
the game is running, and that has its own tools later on.
Watch for
input() always gives back a string. Always. Even 7.
Wrap it in int() before doing arithmetic, or float() if the answer
can have a decimal point.
TypeError on a line with + nearly always means a forgotten int()
above it, or a forgotten str() on the line itself.
ValueError means the typing did not fit — the answer was not a number
at all.
Put a space at the end of the prompt, inside the quotes.
The program stops at every input(). If a program of yours seems to have
frozen, look for a question it is waiting for an answer to.
Classwork 1 — The Greeter
Start here and press Run:
name = input("What is your name? ")
print("Hello, " + name)
What is your name? Ada
Hello, Ada
Then, running after each step:
- Ask a second question — a favourite colour — and print both answers in one sentence.
- Ask for a number of years and store it with
int()around theinput. Print how old they will be in ten years. - Print the name, the colour and the age on three separate lines, with a
label on each:
Name: Ada, and so on. - Run it again and answer
tento the number question. Read the error, and find the word in it that says what kind of thing went wrong.
Stretch: ask for a first name and a last name separately, then print them
joined with a space between. Do it twice — once with + and once with commas
in print — and see which gives you the spacing you wanted without thinking
about it.
Classwork 2 — The Shop
A till that works out a bill.
item = input("What are you buying? ")
how_many = int(input("How many? "))
print("You bought", how_many, item)
What are you buying? sword
How many? 2
You bought 2 sword
- Ask for the price of one, and store it with
float()so that4.5works. - Work out the total in a variable of its own and print it with a label.
- Add a delivery charge of 2.50 to the total, and print the two numbers on separate lines — the goods, then the bill.
- Try answering
twoto the "how many" question, then2. Both errors are in this lesson.
Stretch: ask whether the order is urgent and print the answer back. You
cannot make the program act on it yet — that needs if, which is
lesson 3 — but you can store it and show it.
Check yourself
You run this and type 5, then 3. What does it print?
first = input("First number? ")
second = input("Second number? ")
print(first + second)
First number? 5
Second number? 3
53
Why 53 and not 8?
Neither answer was ever turned into a number. first holds the string
"5" and second holds "3", so + did what + does to two strings:
stuck them together end to end.
This is the nastiest version of the mistake, because nothing goes wrong.
There is no TypeError to read — both sides are strings, so Python is happy
and the answer is simply incorrect. A program that stops and complains is
telling you where to look; this one just quietly says 53.
int() around both inputs fixes it.
← Lesson 1 — Variables · All nine lessons · Lesson 3 — Conditionals →