5 Chapter 5: Printing
PRINTING
Topics Covered:
- The print function
- Rounding
- Format specifiers
The print function
Even when we are working with a text-based user interface (TUI), we would like to design programs that are easy to use and intuitive for the user. In order to do this effectively, it is necessary to understand how to take full control of how you display data on the screen. To begin, we will take a closer look at how Python’s print statement works.
You can see from these examples that the print statement allows any number of parameters, or items between the parentheses. In the first example, there was only one parameter, “dog”. The second example had no parameters so it just printed a blank line. The final two examples each had three parameters. Notice how a space was displayed between each item; this sets Python apart from many other commonly-used programming languages.
If you wanted something other than a space between each item, you can define the separator with the sep attribute of the print statement. Here are some examples of programmer-defined separators:
You can see in each example, the items that were normally separated by a space are now separated by the string that followed sep=. The third example shows how you can use the empty string to print items without any separation. The final two examples begin with a backslash (\) and create what is called an escape sequence. The character that follows the backslash defines a special character. The “\t” produced a tab and the “\n” created a newline.
We have previously seen that each print statement will generate output on a new line. Occasionally, you would like to display something, but you do not want to move the following output to the next line. In this case, you can define how the line should end be setting the end attribute to a string that should terminate the print. Here is an example:
In this code example, the first three print statements are directing each output to be terminated with a space instead of the default new line. Without these three end=” “ clauses, the four print statements would create four lines of output. Instead, the output looks like this:
Rounding Numbers
We introduced the round function in chapter 3. It can be used to round a floating point to the nearest integer. It can also be used to round a floating point number to a specified number of decimal places. It is important to note that when you use round in a print statement with a variable, the value of that variable does not actually change. This example will illustrate the point:
The output when that code segment is executed looks like this:
There are cases in which you would like to store the rounded result of an expression. Perhaps you are rounding a currency expression to the nearest hundredth so you can keep track of dollars and cents. In the following example, we compute the simple interest for an amount of $465.83 deposited in an account earning 4.25% interest for 2.5 years. We will display that interest as calculated, plus rounded using 2 decimal places. Here is the Python code along with the output displayed by the program:
You can either round a previously calculated result, or you can include the round function in the computation, as shown below:
roundedInterest = round(interest,2) # store to a new variable
interest = round(principal*rate*time,2) # round formula
Format Specifiers
Sometimes, rounding alone doesn’t provide enough control over the output’s appearance. Let’s take a look at the simple interest example again, but this time use data that produces an interest value that naturally ends with only one decimal place. Here is the Python code and the sample run:
With a currency amount, we often want two decimal places displayed, along with a dollar sign immediately in front of the amount. Since a space separates the label and number by default, we can use the separator to close the gap. We can use a format specifier to force two decimal places to be printed. Here is the new and improved version, along with the program’s output:
In the example above, the format specifier “%.2f” was placed before the variable interest with a percent symbol, %, separating the two. This expression forces the output to display two digits after the decimal point. Python provides quite a bit of functionality with format specifiers, as illustrated below:
The “%xxd” specifier is used to define the total width of the output field. By default, the result is aligned to the right, or right justified, with spaces attached to the left of the value. The dash (-) can be used to change the alignment to the left so spaces are instead added to the right when integers d, e, and f are displayed:
Python also allows you to combine rounding and field-width specification into a single formatting specification. This is especially useful when you are trying to align numbers into columns. In the Python code below, we will display each of four numbers using two decimal places and a total of seven characters:
In this output, notice that the value 893.00 takes up six characters so one space was added on the left. Also, observe that the decimal points all align vertically, as well as the digits in the tenths and hundredths place.
We have seen how the letter d is used for integers and f is used for floating point numbers. You can use the letter s when formatting string variables or expressions. The alignment for strings is similar to that of integers. In the next example, we will display the first name, last name, and career rushing yards for three former football players. In each case, both the first and last names will be displayed in 10-character fields, aligned on the left. The rushing yards will be displayed in eight-character fields; special formatting is used to specify that commas should be used to separate the numeric values in three-digit groups.
INTERACTIVE – Formatting output
Look at the code snippet below and try to predict the output. Run the program and check your guess. Take a look at the code where there is a backslash and consecutive double quotes after the height is printed. Can you figure out what’s going on?
As noted ahead of the example, a different technique was used to control the appearance of the rushing yards. Python provides a number of different mechanisms for controlling the format of your output. In the following example, three different techniques are used to display a floating-point value in a field that is six characters wide, and allows two digits after the decimal point. We believe that the first method, %-formatting, is the easiest to understand, and will be more than adequate for our needs. To learn more about the other two mechanisms, the format() method and the f-string, you can consult other resources, including books and websites.
The corresponding output:
With a Python f-string, you can put expressions between curly brackets {}. In the example below, we print an f-string that includes the variables this and that, as well as their product this*that:
You can use f-strings to specify the spacing and precision of variables or expressions that you want to display. Below we print the value of the floating point variable named number, first with 1 decimal place, then with 5 decimal places:
Chapter Review Exercises:
5.1. Show the exact output of the Python code (use ^ to indicate spaces):
amount1 = 25.8888
amount2 = 4
amount3 = 382.62
amount4 = 843.676767
print(“%8.3f”%amount1)
print(“%8.3f”%amount2)
print(“%8.3f”%amount3)
print(“%8.3f”%amount4)