Every program you have written so far has been a monologue. It runs from top to bottom and tells the user things, but the user never gets a word in. Input turns a program into a conversation: it is the data the program collects so that it has something of its own to work with.
Programmers describe what a program does in three stages, and input is the first of them.
In this course the input is always the user typing on a keyboard, but a computer collects input in plenty of other ways: as sound through a microphone, as mouse movements, or through sensors.
Python collects typed input with input(). When Python reaches an input() it
stops and waits. Nothing else happens until the user has typed something and
pressed enter. Whatever they typed then comes back as the result of the
input().
print("What's your name?")
name = input()
print("Hello " + name)
If the user types Andy and presses enter, the screen looks like this:
What's your name?
Andy
Hello Andy
The middle line is not something the program printed. It is the user’s own typing, appearing on the screen as they type it.
A question is asked with its own print, and input() on the next line only
waits for the answer: printing the question and collecting the answer are two
separate steps.
input() collects a piece of data, but it does not store that data anywhere by
itself. Assignment is what stores it. If you leave out the variable and the =,
Python reads what the user typed and then throws it away:
print("What's your name?")
input()
print("Hello")
That program still waits for the user, and the user still types a name, but nothing anywhere remembers it, so there is no way to ever use it again.
Input must always be assigned to a variable, or it is discarded. This is the
single most common mistake with input(), and it is a quiet one: the program
does not crash, it just forgets.
Whatever the user types comes back as a string, even when it looks like a
number. The + symbol therefore concatenates it rather than adding it up:
print("How old are you?")
age = input()
print(age + age)
How old are you?
12
1212
That is not 24. The user typed 12 once, and age + age joined that text to
itself rather than adding it up, because age holds the text "12" and not the
number 12. Turning text into a number so that you can calculate with it is
called casting, and it comes later in this course.
Run the code below and answer both questions. Then change the questions, and the sentences that use the answers, and run it again.
print("What's your name?")
name = input()
print("Hello " + name + "!")
print("What's your favourite food?")
food = input()
print("I like " + food + " too, " + name + ".")