(Aim to complete this during your lab in week 5.)

Learning Objectives

· to gain practice in simple formatting of output

· to learn how to use the math module

Make a new folder called Lab 4 in your Labs folder. All the example programs that you develop during this lab should be kept in this folder.

Simple String Formatting

**Table of Squares and
Cubes**

Use **New Window** from the **File** menu of the Python shell to obtain an editor window.
Paste the following code into the window.

""" squares.py formatted output of squares created by sands 30/10/10 """ i = 1 line = "" while i<=10 : line = line + format(i, "4d") i = i + 1 print(line) i = 1 line = "" while i<=10 : line = line + format(i*i, "4d") i = i + 1 print(line)

Save the program as squares.py in your Lab 4 folder.

Run the program.

Observe that it generates two lines of output - the first line contains the numbers from 1 to 10 and the second contains their squares. The columns are correctly aligned.

Study the program code - each line has been generated using a loop. Within the
loop we have used the format function to perform
the desired formatting of the string. This function takes two arguments, an
expression and a format string, and returns a string containing the value of the
expression, formatted according to the second argument. The use of
"4d"
indicates that we wish to display the number as a decimal integer with a *
field width* of 4 (i.e. the generated string should contain 4 characters with leading spaces if necessary).

Change both occurrences of the format string to "3d" and run the program again. This time the output does not look as pleasant since there is no space before the last number on the second line.

Now change both occurrences of the format string to "<3d" and run the program again. This time the numbers are left-aligned - spaces have been added after the digits where necessary.

Add to the end of the program another block of code (similar to the last six lines) to generate and output a string containing the cubes of the numbers. Run and test.

Now change all occurrences of the format string to "^5d" and run the program again. This time the numbers have been centre-aligned (look at the fifth column to see this - centre-alignment doesn't look very neat when some of the numbers have an even number of digits).

Close the editor window.

**Formatting Real Numbers**

In the shell window type the line

from math import pi

then type

pi

The value of π should be displayed.

Now type

format(pi, "10d")

An error will be reported - we cannot format real numbers using the d format specifier, but have to use f instead.

Type

format(pi, "10f")

Observe that a string is displayed. The shell window displays the value of the expression; if we wanted to output the contents of the string (without the quotes) we would have to use print(format(pi, "10f")).

Now try

format(3.8, "10f")

The strings generated in this and the previous example both contain ten characters; we observe that by default the format function prints real numbers with 6 decimal places so two leading spaces are needed to complete the field width.

Now try

format(pi, "6.3f")

This time we have specified that we wish to use a total of six characters with three digits after the decimal point. One leading space is included to make up the six characters.

Finally try

format(pi, "4.3f")

Observe that the string returned by the call contains more than four characters - the value for the field width specifies a minimum value; if the value of the expression does not fit into a string of this length a longer string will be generated.

**Formatting Strings**

Open a new editor window and paste into it the following code

""" people.py formatted output of names and ages created by sands 30/10/10 """ print(format("First name", "12s") + format("Second name", "12s") + format("Age", "4s")) print(format("Monty", "12s") + format("Python", "12s") + format(40, "4d")) print(format("Bart", "12s") + format("Simpson", "12s") + format(13, "4d"))

Save the program as people.py in your Lab 4 folder.

Examine the program. We want to generate a neat table of names and ages. Observe that s is used as the format specifier when formatting strings.

Run the program. The output is not quite what we would want. Strings are by default left-aligned (with trailing spaces added where necessary) whereas numbers are by default right-aligned. We need the string "Age" to be right-aligned. To do this you should modify the last format string in the first call to print to ">4s".

Add above the first print statement code to input from the keyboard the first name, second name and age of two more people and store these in variables such as fname1 and age2.

Add to the end of the program two more calls to print to output the details of these two extra people (using the same formatting strings as on the last line).

Run and test, supplying names less than 12 characters in length.

Now run again and supply as input a name that contains more than 12 characters. The output will not look very neat. We cannot prevent the user from supplying a long name so we may wish to truncate the output. Change all occurrences of "12s" to "12.12s". and run again with long names as input.

This time the output looks better. When a string is formatted using
*m*.*n*s the first digit is a minimum
field width and the second is a maximum one. If the length of the string
supplied as the first argument to format exceeds
the maximum a truncated string is returned.

Close the editor window.

Using the math Module

**Calculating Circumferences and Areas of Circles**

Obtain a new editor window and paste into it the following code

""" circle.py circumference and area calculation created by sands 30/10/10 """ from math import pi def circ(diam) : """ calculates circumference of circle argument: diam (diameter) : float returns: circumference : float """ return(pi * diam) def area(diam) : """ calculates area of circle argument: diam (diameter) : float returns: area : float """ radius = diam/2 return(pi * radius * radius) myDiam = float(input("Specify diameter: ")) print("Length of circumference is", format(circ(myDiam), ".3f")) print("Area is", format(area(myDiam), ".3f"))

Save the program as circle.py in your Lab 4 folder.

This program contains functions to calculate the circumference and area of a
circle using the formulae *circ* = π*d*
and *area* = π*r*^{2}.
The functions take the diameter as an argument - since the second formula
requires the radius, the second function must first calculate this.

We have to import the value of π from the math module; hence the program contains the statement from math import pi.

I have chosen this time to use the format function to specify the number of decimal places; it would have been possible to use round instead.

Run the program several times with different inputs.

Delete the last three lines and replace them with code that uses a loop to
generate output of the form

Diam Circum Area

0.5 1.571 0.196

1.0 3.142 0.785

1.5 4.712 1.767

The table should contain 20 rows, with diameters from 0.5 to 10.0 and you should use the format function to make sure that all outputs are right-aligned in a neat table.

**Calculating the Radius from the Area**

We now wish to add to the program an extra function to calculate the radius of a circle whose area is known.

The radius is the square root of *area*/π; to
obtain squire roots
so we need to use
the
sqrt
function from the
math module and must hence import this. Modify the end of the statement
that imports the value of π so it now reads

from math import pi, sqrt

Define a new function with structure

def rad(area) :

"""

appropriate documentation

"""

return ...

The value to be returned is the square root of *area*/π;
write an appropriate expression in the return statement. (The
sqrt function
takes an argument of type float
and returns a result of type float.)

Add to the end of your program some code that will input areas of circles from the keyboard, call the new function to calculate their radii, and display the results.

Run and test.

**Calculating Logarithms**

Obtain a new editor window and paste into it the following code

""" log.py calculation of logarithms base 2 of 2, 4 ... 16 created by rturner 31/10/10 modified by sands 1/11/10 """ from math import log10, log string = format('x','>6s') + format('log2 x', '>12s') print(string) x = 2 while x <= 16 : string = format(x, '6d') + format(log(x,2), '12.3f') print(string) x = x + 2

Save the program as log.py in your Lab 4 folder and run it

This program displays a table with the value of log_{2}*x*
(pronounced "log to the base 2 of x") for values of *x* from 2 to 16.

It uses the log function from the
math module - this takes two arguments, the
number whose logarithm is required and the base. Both should be of type
float, but we can use an integer when an
expression of type float is required; an
implicit conversion will be performed. The second argument may be omitted, in
which case the natural logarithm of the number (i.e. the logarithm to the base
*e*) will be returned. [ Don't worry if you don't understand what a
logarithm is - it doesn't matter for this exercise! ]

Since mathematicians most frequently use, in addition to natural logarithms,
logarithms to the base 10, there is an extra function called
log10 to calculate log_{10}*x*;
this takes just one argument, the value for *x*.

Modify the program so that the table has three columns, showing *x*, log_{10}*x*
and log_{2}*x* (using the log10
function to calculate log_{10}*x*).

Run, and check that the output still looks neat and appears to be correct - the
value for log_{10}2 should be 0.301 and the value for log_{10}16
should be 1.204.

Add extra code to the beginning of the program to allow the user to supply as input the first and last values of x, and the step (i.e. amount by which x should be incremented)

**If you complete these exercises before the end of the lab session you should
use the remainder of the lab to start or continue working on assignment 1.**