We write programs so they can produce useful results. We’ll start with statements that immediately satisfy our goal: seeing the results. We’ll cover the basic print statement in The print() Function. We’ll add some useful features in Dressing Up Our Output.
Yes, this chapter is really short; the print statement is delightfully simple.
In Python 3, the print statement will be replaced with a slightly simpler print() function. To align the the future, we’ll focus on the function version of print, and avoid the statement.
The print() function takes a list of values and, well, prints them. It converts numbers and other objects to strings and puts the characters on a file called standard output. Generally, this standard output file is directed to the Python Shell window in IDLE. If you run Python directly, it is directed to the Terminal (or Command Prompt) window where Python was started.
When we are interacting with Python at the >>> prompt and we give Python an expression, the result is printed automatically. This is the way Python responds when interacting with a person. When we run script, however, we won’t be typing each individual statement, and Python won’t automatically print the result of each expression. Instead, we have to tell Python to show us results by writing an statement using the print() function that shows the response we want.
The print() function isn’t automatically available in Python 2. It will be automatically available in Python 3.
To use the print() function, we need to include the following statement.
from __future__ import print_function
This must be the first statement in a script. It alerts Python that we won’t being using the print statement, and we will be using the print() function.
The basic print() function looks like this:
The print() function converts each value to a string and writes them to the given file (by default it’s standard output).
Statement Syntax Rules
We used an ellipsis (...) to indicate something that can be repeated. There’s no real upper limit on the number of times something can be repeated.
We used sep=’ ‘ to show two things. First, if this parameter is used, it must be given by name. Second, the parameter has a default value. That meas it can be safely ignored for now.
Here are some examples of a basic print() function.
from __future__ import print_function print(22/7, 22./7.) print(335/113, 335./113.) print( ((65 - 32) * (5 / 9)) )
We’ll look at the special purpose sep, end and file arguments separately. For now, it’s important to note that they have default values, making them optional.
The print statement takes a list of values and, well, prints them. It converts numbers and other objects to strings and puts the characters on a file called standard output.
The basic print statement looks like this:
print expression [ , expression ] ...
The print statement converts the expressions to strings and writes them to standard output.
Statement Syntax Rules
We’ll show optional clauses in statements by surrounding them with [ and ]‘s. We don’t actually enter the [ ]‘s, they surround optional clauses to show us what alternative forms of the statement are.
We use a trailing ellipsis (...) to indicate something that can be repeated. There’s no real upper limit on the number of times something can be repeated.
Also notice that we put a , before the expression. This is your hint that expressions are separated with , characters when you have more than one.
In the case of print, the syntax summary shows us there are many different ways to use this statement:
While our summary doesn’t show this, there are several other forms for the print statement. All of the extra syntax options and quirks of the print statement are really just fodder for confusion.
Here are some examples of a basic print statement.
print 22/7, 22./7. print 335/113, 335./113. print ((65 - 32) * (5 / 9))
We’re mostly going to ignore the print statement because the print() function does the same thing and has no quirks or odd special cases.
We can make our printed output easier to read by including quoted strings. See Strings – Anything Not A Number to review how we write strings.
For example, the following trivial program prints a string and a number. Since our string had an apostrophe in it, we elected to surround the string with quotes (").
from __future__ import print_function import math print( "The answer:", 6*7 ) print( 'Value of "pi":', 6.0/5.0*( (math.sqrt(5)+1) / 2 )**2 )
It’s very important to note that the from __future__ import print_function must be provided first.
Debugging the print Statement
One obvious mistake you will make is misspelling print. You’ll see NameError: name 'primpt' is not defined as the error message. I’ve spelled it “primpt” so often, I’ve been tempted to rewrite the Python language to add this as an alternative.
The other common mistake that is less obvious is omitting a comma between the values you are printing. When you do this, you’ll see a SyntaxError: invalid syntax message.
If the result of a print statement doesn’t look right, remember that you can always enter the various expressions directly into IDLEs Python shell to examine the processing one step at a time.
Print Expression Results.
In the Conversational Python Exercises exercises in Instant Gratification : The Simplest Possible Conversation, we entered some simple expressions into the Python interpreter. Change these expressions into nice-looking print() statements.
Be sure to print a label or identifier with each answer. Here’s a sample.
print( "9-1's * 9-1's = ", 111111111*111111111 )
The print() function’s default is to put a space between items, which may not always be desirable.
The string formatting method provides complete control over the formatting of data. We’ll cover this in depth in Sequences of Characters : str and Unicode. First, we want to introduce a number of programming statements. Once we’ve got more of the language under our belt, we’ll tackle the “fit and finish” issues of nicely formatted output.
However, if you can’t wait until then, we’ll provide some hints as to what will come in the future.
from __future__ import print_function print( "from this", "via that", "to this", sep="->" )
We’ll talk about this in detail in External Data and Files. However, if you can’t wait until then, we’ll provide some hints as to what will come in the future.
from __future__ import print_function import sys print( "an error", file=sys.stderr )
The print() function’s default is to put a newline character at the end, which may not always be desirable.
If we change the end parameter, we can piece together a long line of output from multiple uses of the print() function. In the following example, the first statement uses ': ' instead of the newline character; the print statement will create a partial line.
from __future__ import print_function print( "335/113", end=': ' ) print( 335.0/113.0 )
If we have very complex expressions, this can make our program easier to read by breaking a complex message into understandable chunks.
This is not obvious when working with Python at the >>> prompt. When we turn to scripts (in the next chapter), we’ll see more use for this.