Exercise 3.1

Objectives:

  • Learn how to organize a program into a collection of functions.

  • Bottom-up program organization.

Files Created: None.

Files Modified: report.py

Overview

In section 2, you wrote a program called report.py that printed out a report showing the performance of a stock portfolio. This program consisted of some functions. For example:

# report.py
import csv

def read_portfolio(filename):
    '''
    Read a stock portfolio file into a list of dictionaries with keys
    name, shares, and price.
    '''
    portfolio = []
    f = open(filename)
    f_csv = csv.reader(f)
    headers = next(f_csv)

    for row in f_csv:
        record = dict(zip(headers, row))
        stock = {
            'name' : record['name'],
            'shares' : int(record['shares']),
            'price' : float(record['price'])
        }
        portfolio.append(stock)
    f.close()
    return portfolio
...

However, there were also portions of the program that just performed a series of scripted calculations. This code appeared near the end of the program. For example:

...

# Output the report

headers = ('Name', 'Shares', 'Price', 'Change')
print '%10s %10s %10s %10s'  % headers
print ('-' * 10 + ' ') * len(headers)
for row in report:
    print '%10s %10d %10.2f %10.2f' % row
...

In this exercise, we’re going take this program and organize it a little more strongly around the use of functions.

(a) Structuring a program as a collection of functions

Modify your report.py program so that all major operations, including calculations and output, are carried out by a collection of functions. Specifically:

  • Create a function print_report(report) that prints out the report.

  • Change the last part of the program so that it is nothing more than a series of function calls and no other computation.

(b) Creating a function for program execution

Take the last part of your program and package it into a single function portfolio_report(portfolio_filename, prices_filename). Have the function work so that the following function call creates the report as before:

portfolio_report('Data/portfolio.csv', 'Data/prices.csv')

In this final version, your program will be nothing more than a series of function definitions followed by a single function call to portfolio_report() at the very end (which executes all of the steps involved in the program).

By turning your program into a single function, it becomes easy to run it on different inputs. For example, try these statements interactively after running your program:

>>> portfolio_report('Data/portfolio2.csv', 'Data/prices.csv')
... look at the output ...
>>> files = ['Data/portfolio.csv', 'Data/portfolio2.csv']
>>> for name in files:
        print format(name,'-^43s')
        portfolio_report(name, 'Data/prices.csv')
        print

... look at the output ...
>>>
Links