In Getting Raw Input we’ll introduce a primitive interactive input function. We’ll look at another function for input in Another Kind Of Input. This will finish up the statements we need to fill out the “input-process-output” pattern for simple programs. We’ll provide some additional notes in Additional Notes and Caveats and the formal definitions for these functions in Input Function Definitions.
To make complete use of this, we’ll need to digress on the standard input, output and error files in The Standard Files.
The material on the del statement in The del Statement is here for completeness. Logically, there’s a nice symmetry between creating variables with the assignment statement, setting values with input functions and removing variables with the del statement. As a practical matter, however, we rarely need to remove a variable.
We’ll answer some additional questions in Input FAQ.
Python provides simplistic built-in functions to accept input and set the value of variables. These are not really suitable for a professional-quality application, but they will help us learn the language. The more robust and reliable input functions are generally embedded in a web-based application, or a sophisticated GUI, both of which are way beyond what we can cover in this book.
These input functions will gather data from a file called standard input. Generally, this standard input file is your keyboard, and the results will show on the Python Shell window in IDLE. If you run Python directly, the Terminal (or Command Prompt) where Python was started will manage reading characters from your keyboard.
Raw Input. By “raw”, we mean unprocessed, unevaluated or uninterpreted. The input is what the person typed; it isn’t every keystroke, it’s the finished product of typing and backspacing. But it’s always a string without further interpretation as a number or date.
We can draw a useful parallel with the Japanese delicacy called Sashimi. Sashimi has been cut and prepared by a chef; it’s not like they throw a big old salty, bleeding salmon down on your table. Similarly, the user’s input to the raw_input() function has been sliced up into individual lines of input by the operating system, and backspaces have been handled graceefully, but little beyond this has been done.
The OS will handle the enter key for you. Plus it also makes sure that the backspace operates as we expect.
We have to talk about the raw_input() from two distinct points of view.
An Example Script. Here’s a very small script that uses raw_input() that produces a prompt, reads and prints the result. This will give you a sense of the two worlds in which this function lives: the world of user interaction as well as the world of Python function evaluation.
Create the following file, named rawdemo.py. Save it and then run it in IDLE using the Run Module item in the Run menu.
# get the user's answer answer= raw_input( "continue?" ) print "You said:", answer
When we run this script, it looks like the following.
continue? why not? You said: why not?
We entered why not?. When we hit enter, we told the operating system that our input line was complete. The OS hands the completed input line to Python. Python then returns this string as the value of the raw_input() function.
Our program saved the value from raw_input() int the variable answer. The second statement printed that variable.
In Python 3, this function will be named input().
Making Raw Input Useful. If we want numeric input, we must convert the resulting string to a number. In the following example, we’ll use the int() and float() functions to convert the strings we got from the raw_input() function into numbers that we can use for calculation.
We’ll use the raw_input() and int() functions to get a number of shares. The resulting number is assigned the name shares. Then the program uses the raw_input() and float() functions to get the price.
Create the following file, named stock.py. Save it and then run it in IDLE using the Run Module item in the Run menu.
# Compute the value of a block of stock shares = int( raw_input("shares: ") ) price = float( raw_input("dollars: ") ) print "value", shares * price
Here’s what we saw when we ran this program in IDLE.
shares: 150 dollars: 24.18 value 3627.0
Exceptional Input. Exceptions, in Python, mean exceptionally bad. The raw_input() mechanism has some limitations. If the string returned by raw_input() is not suitable for use by int(), an exception is raised and the program stops running.
Here’s what it looks like when we ran stock.py and provided inappropriate input values.
In addition to the raw_input() function, which returns the exact string of input characters, we also have the input() function. This function takes one more step beyond what raw_input() does. After reading the input, the input() function then applies the Python eval() function to evaluate the input string and create a proper Python object.
The point is to automatically convert a string of digits to a proper numeric value. The following two sequences of statements are identical.
v = eval( raw_input( 'enter a number:' ) )
v = input( 'enter a number:' )
The reason why Python 2 has this function is because we sometimes like to decode a string of digits as an integer. Further, we expect that digits plus a period will become floating-point number.
We’ll avoid input(), since it’s going away in Python 3.
If you try to run these examples from TextPad, you’ll see that TextPad doesn’t have any place for you to type your input. You’ll get an immediate end-of-file error. Why does this happen? It happens because TextPad doesn’t have a proper file for standard input. Since the file doesn’t exist, we get an immediate error when we try to use it.
For MacOS users using tools like BBEdit, you’ll can use the Run In Terminal item in the #! menu to create a Terminal window for your interaction. This new window appears when your run your script, showing your standard input and giving you a place for standard input.
Debugging the raw_input() Function
There are two kinds of mistakes that occur. The first kind of mistake are basic syntax errors in the raw_input() function call itself.
The other mistake, which is more difficult to prevent, is to provide invalid input to the script when it runs. Currently, we don’t quite have all of the language facilities necessary to recover from improper input values. When we cover the try statement and exception processing in The Unexpected : The try and except statements we’ll see how we can handle invalid input.
In the long run, we’ll see that the raw_input() function is not the most reliable tool. For simple programs, problems with raw_input() are easily solved. If you give your software to someone else, the vagaries of what is legal and how Python responds to things that are not legal can be frustrating for them to learn.
Professional quality software doesn’t make much use of these functions. Typically, interactive programs use a complete graphic user interface (GUI), often written with the Tkinter module or the pyGTK module. Both of these are beyond the scope of this book: they aren’t newbie-friendly modules.
Here are the formal definitions for these two functions.
Read a string from standard input. If a prompt is given, it is printed before reading. If the user hits end-of-file (Ctrl-D in GNU/Linux or MacOS; Ctrl-Z in Windows), an exception is raised.
In Python 3, this will be renamed input().
Read a string from standard input and then evaluates that string with the eval(). If a prompt is given, it is printed before reading. If the user hits end-of-file (Ctrl-D in GNU/Linux or MacOS; Ctrl-Z in Windows), an exception is raised. If the input not a valid Python-language literal, an exception is raised. This means that strings must be input with quotes.
In Python 3, this will go away.
We need to take a quick digression to look at how your keyboard really works. Generally, we take our keyboard for granted: we start an application, we type and the letters appear. After a while, you get used to letters only showing up in the front-most window. Our operating system tells us which window is active by providing a number of visual cues like bringing the window to the font, showing a blinking cursor and a fancier frame around the window.
Under the hood, your operating system is watching your keyboard device for activity. Most of the buttons on your keyboard generate an “event`. Some of the buttons are “modifiers”: the shift, alt, command, and control keys modify the basic key event. The operating system routes these key events to the front-most window. The application program that displays the front-most window is responsible for making sense of the events.
Why “events”? Why not just “characters”? The reason is that some programs don’t have characters. A game, for example, doesn’t want characters, it wants events that will make the pinball flippers flip, or the person walk.
For many programs, most of these events will be interpreted as characters. There are two really common events that are not characters: the backspace event and the enter event are not letters; instead, they change the sequence of characters being accumulated. The front-most window has to do something with events like backspace. What most of us expect is that backspace removes the previously accumulated character. The enter key alerts the program that you are finished typing and are ready for the program to see the input letters.
Plus, when you look at your keyboard, you’ve got a dozen (or more) F-keys, plus keys with names like Insert, Delete, Home, End, etc. These are not characters in the same sense as the other keys. These extra keys are used by IDLE to control your interactive Python session. When you run Python from the Command Prompt or Terminal tool, you’ll see that these extra F-keys do little or nothing. In the Windows Command Prompt, you can use a program named doskey to define actions for these non-letter keys. In the MacOS, there are a number of programs that use these additional F-keys for a variety of purposes; for instance, F12 brings up my dashboard.
Redirection. Each shell also has ways to change the origin of the characters available on standard input. When you redirect standard input, it means that your program will wind up reading from a disk file instead of the keyboard. In The print Statement, we mentioned the file called standard output. Standard output is like standard input: it was opened for you, and it can be redirected outside your program.
This shell redirection technology allows a single program to read from a disk file or read from the keyboard without any changes to the program; there is just a small change to the shell command that starts the program. Similarly, it also allows a program to write the terminal window, or write to a disk file depending on settings provided to the shell. While the details of controlling the shell are outside the scope of this book, the idea is that one program can do any of the preceding, with no change to the program. This gives us a lot of flexibility for no real cost or complexity in our programming.
Refer back to the exercises in Expression Exercises for formulas and other details. Each of these can be rewritten to use variables and an input conversion. For example, if you want to tackle the Fahrenheit to Celsius problem, you might write something like this:
C = input('Celsius: ') F = 32+C*float(9/5) print "celsius",C,"fahrenheit",F
Input the number of shares, dollar price and number of 8th’s. From these three inputs, compute the total dollar value of the block of stock.
Convert from ° C to ° F.
Write a short program that will input ° C and output ° F. A second program will input ° F and output ° C.
Input the principal, annual percentage rate and number of payments. Compute the monthly payment. Be sure to divide rate by 12 and multiple payments by 12.
Surface Air Consumption Rate.
Write a short program will input the starting pressure, final pressure, time and maximum depth. Compute and print the SACR.
A second program will input a SACR, starting pressure, final pressure and depth. It will print the time at that depth, and the time at 10 feet more depth.
Input a temperature and a wind speed. Output the wind chill.
Force from a Sail.
Input the height of the sail and the length. The surface area is . For a wind speed of 25 MPH, compute the force on the sail. Small boat sails are 25-35 feet high and 6-10 feet long.
An assignment statement creates a variable, or assigns a new object to an existing variable. This change in state is how our program advances from beginning to termination. Python also provides a mechanism for removing variables, the del statement. This version of the statement is used rarely; we describe it here to close the circle of the life for a variable.
The most common use for the del statement is to remove individual elements from a list object. We’ll revist this statement when we look at lists in Flexible Sequences : the list. There, we’ll find a more practical use for this statement.
The del statement looks like this:
del target 〈 , ... 〉
A target is a name of a Python object: a variable, function, module or other object. The variable is removed. Generally, this also means the target object is removed from memory.
The del statement works by unbinding the name, removing it from the set of names known to the Python interpreter. If this variable was the only reference to an object, the object will be removed from memory also. If, on the other hand, other variables still refer to this object, the object won’t be deleted.
Debugging the del statement
If we misspell a variable name, or attempt to delete a variable that doesn’t exist, we’ll get an error like NameError: name 'hack' is not defined.
We’ll take a quick survey of four overall architectures where you will be interacting with your computer. What we want to emphasize is the tremendous differences between these architectures. Since there is so little in common, Python doesn’t have a newbie-friendly, reliable, flexible, and richly interactive input mechanism.
With these styles of programming having so little in common, there’s very little built-in to the Python language to support a user interface. For all but the first case (command-line utilities), you’ll have to master some kind of add-on package appropriate to the kind of programs you want to write.