|
CS 140: Introduction
to Computer Programming
Formatting
Output
At times it is desirable to display output on
the screen in an organized manner; for instance,
when creating a table or chart. There are
several techniques for accomplishing this.
Python has a built in tabbing system that can be
utilized by typing \t
at any point within quotes. This command
has the effect of lining up text in columns
beginning every eight spaces. It is best
understood via a couple of examples. The
statements
print "\t*\t*\t*\t*"
print "\tMe\tMyself\tand\tI"
print "Merry\tChristmas\t
and\tHappy New Year"
will result in the output
*
* *
*
Me
Myself and I
Merry
Christmas
and Happy New Year
The asterisks highlight the locations to which
the cursor advances; they are the tab
stops. Notice on the third line that
because the word `Christmas' was so long it
extended past the second tab stop, so when the \t
command was encountered the cursor advanced to
the next available location, which was the third
tab stop. You probably also noticed that
the word and
did not align properly—that's because there was
a space before the and
in the third line of code. Moral of the
story: spaces always count inside quotes!
The newline command \n
will print carriage returns. In other
words, it will advance the cursor to the start
of the next line. We will use both tabs
and newline commands in the next example to
create a tidy chart that displays how much a 15%
or 18% tip would be for various amounts.
print "\n\n\t
Tipping Chart"
print "\n\t Bill\t 15%\t 18%"
for bill
in range(3,31,3):
print "\t", bill, "\t", bill*.15, "\t", bill*.18
print "\n\n"
The newline commands insert a little blank space
above and below the chart, so that it stands
alone on the screen. Notice that the space
before Bill
in line 2 appears, but the commas in line 4 do
not insert extra spaces after the tabbing.
The output looks like this.
Tipping Chart
Bill
15% 18%
3
0.45 0.54
6
0.9 1.08
9
1.35 1.62
[etc.]
30 4.5
5.4
|
|
|