[Tutor] making a table
alan.gauld at freenet.co.uk
Fri Sep 9 12:26:36 CEST 2005
>I would like to construct a table for my program but it does not seem
> coming out evenly. Could someone please let me know what to do so
> everything will work out correctly?
The best way to build a table is to use a format string with every
field width specified explicitly. Thus in your example:
"""This program prints a table of Celsius temperatures
and their Fahrenheit equivalents """
fmt = "%4s %4s"
print fmt % ('C','F')
for i in range(min, max, step):
fahrenheit = (9.0/5.0) * i + 32
print fmt % (i,farenheit)
By applying the same format to the headings you ensure consistency and
by specifying the widths you get guaranteed text line-up. If you want
to print an HTML table you only need to add the tags to the format
string (although in that case you might want a different format
for the header)
I also parameterised the function so you can specify the range of
temperatures and the step size just for fun. :-)
More information about the Tutor