2.1.6.1 How to talk to a computer
The input() function
We're now going to introduce you to a completely new function, which seems to be a mirror reflection of the good old
print()
function.
Why? Well,
print()
sends data to the console.
The new function gets data from it.
print()
has no usable result. The meaning of the new function is to return a very usable result.
The function is named
input()
. The name of the function says everything.
The
input()
function is able to read data entered by the user and to return the same data to the running program.
The program can manipulate the data, making the code truly interactive.
Virtually all programs read and process data. A program which doesn't get a user's input is a deaf program.
Take a look at our example:
print("Tell me anything...")
anything = input()
print("Hmm...", anything, "... Really?")
It shows a very simple case of using the
input()
function.
Note:
- The program prompts the user to input some data from the console (most likely using a keyboard, although it is also possible to input data using voice or image);
- the
input()
function is invoked without arguments (this is the simplest way of using the function); the function will switch the console to input mode; you'll see a blinking cursor, and you'll be able to input some keystrokes, finishing off by hitting the Enter key; all the inputted data will be sent to your program through the function's result; - note: you need to assign the result to a variable; this is crucial - missing out this step will cause the entered data to be lost;
- then we use the
print()
function to output the data we get, with some additional remarks.
Try to run the code and let the function show you what it can do for you.

Comments
Post a Comment