Reading what the user types
Your Hello, world program from lesson 1-2 only produced output. Real programs also take input, the first corner of the input → process → output triangle from lesson 1-1.
Python's built-in instruction for input is input(). When the interpreter reaches input(), it pauses, waits for a line of typed text, and then hands that text to your program.
Where that text comes from is called standard input, usually shortened to stdin. It is the traditional name for the stream of text a program reads, and normally it is whatever the person at the keyboard types. The examples below show the stdin a program was given along with the output it produced, so you can see both halves at once.
One more trick: print can show several things at once if you separate them with a comma, and it automatically puts a space between them.
print("You typed:", input())
Read it inside-out. input() grabs the typed text first, then print shows the label and the text together.
Input reaching the program
Here the program is given the line hi there on standard input.
print("You typed:", input())
Input
hi there
Output
You typed: hi there
Change the input and the output changes with it, which is the whole point of input. The program's instructions stayed identical, and the result did not.
That is the first genuinely useful property of a program. A program that only prints Hello, world! is a fixed announcement, and a program that reads input is a machine that handles cases its author never saw.
What input does when the program runs
input() pauses and reads one line of typed text, handing it to the program.
That is how a program listens. It reads a single line, stops at the end of it, and gives the text to your code to use.
The three roles are now complete and each has a name. print is for output, input() is for input, and your instructions in between are the process from lesson 1-1.
Worth noticing: input() reads one line, not one word and not the whole rest of the typing. Reading two lines takes two calls, which is the sort of small exactness that turns into a bug the first time you forget it.
Echoing a word back with a label
Given the word banana on standard input, this program prints it after a label.
print("Echo:", input())
Input
banana
Output
Echo: banana
Reading the pieces
- The pattern is the same as the previous example with different label text. Recognizing a pattern you can vary is more useful than memorizing either version.
print("Echo:", input())reads the word and prints it after the label, with a space between them supplied by the comma.- The label is written with no trailing space inside the quotes. The space in the output comes entirely from the comma, so adding one inside the quotes would give two.