This section shows a complete, well commented program to indicate how most of the ideas discussed so far (Variables, Arrays, Files, etc.) are used together.
Below is a rewritten version of the example in Section 3.2, which did nothing more than add two numbers together. However, the two numbers are stored in arrays, the numbers are read in by a separate function, the addition is also done by a separate function, and the result is written to a file.
from Numeric import * def addnumbers(x, y): # Declare functions first. sum = x + y return sum def getresponse(): # Create a two element array to store the numbers # the user gives. The array is one of floating # point numbers because we do not know in advance # whether the user will want to add integers or # floating point numbers. response = zeros(2, Float) # Put the first number in the first element of # the list: response = input("Please give a number: ") # Put the second number in the second element: response = input("And another: ") # And return the array to the rest of the program return response # Allow the user to name the file. Remember this is a string # and not a number so raw_input is used. filename = raw_input("What file would you like to store the result in?") # Set up the file for writing: output = open(filename, "w") # Put the users response (which is what the getresponse() function # returns into a variable called numbers numbers = getresponse() # Add the two elements of the array together using the addnumbers() # function answer = addnumbers(numbers, numbers) # Turn the answer into a string and write it to file stringanswer = str(answer) output.write(stringanswer) # And finally, don't forget to close the file! output.close()
The following function computes by summing the Taylor series expansion to terms. Write a program to print a table of using both this function and the
exp() function from the
library, for x = 0 to 1 in steps of 0.1. The program should ask the user
what value of to use.
def taylor(x, n): sum = 1 term = 1 for i in range(1, n): term = term * x / i sum = sum + term return sum
This is the end of the introduction to Python. Talk to a demonstrator who will be able to suggest a problem for you to attempt (or you may choose the one you did last year but please talk to a demonstartor first). If the problem requires graphical output then you will need to refer to Section 4.1 which provides an introduction to the use of the Gnuplot package from within Python. The rest of Chapter 4 discusses material that is either considered to be ``additional'' to the basic core knowledge presented in this chapter or that is peculiar to programming in Python. Whilst it is not required reading at this stage, you should at least glance over it now so that you can refer to it later if necessary.