Exercise 1.7 - Solution

(b) Defining a function

# pcost.py

def portfolio_cost(filename):
    '''
    Computes the total cost (shares*price) of a portfolio file
    '''
    total_cost = 0.0

    f = open(filename)
    for line in f:
        row = line.split(',')
        nshares = int(row[1])
        price = float(row[2])
        total_cost +=  nshares * price
    f.close()
    return total_cost

(c) Adding some error handling

# pcost.py

def portfolio_cost(filename):
    '''
    Computes the total cost (shares*price) of a portfolio file
    '''
    total_cost = 0.0

    f = open(filename)
    for line in f:
        row = line.split(',')
        try:
            nshares = int(row[1])
            price = float(row[2])
            total_cost += nshares * price
        # This catches errors in int() and float() conversions above
        except ValueError:
            print 'Bad line:', repr(line)
    f.close()
    return total_cost
Tip

The repr(x) function is useful for producing output-related to debugging. Instead of simply printing a value in the normal way, it shows you the representation of the value as it would appear in code. For strings, you’ll see escape codes and other low-level details not easily visible with a normal print statement. This is handy if you’re trying to debug problems related to data parsing as you can easily see the representation of the raw data.

(d) Using a library function

# pcost.py

import csv
def portfolio_cost(filename):
    '''
    Computes the total cost (shares*price) of a portfolio file
    '''
    total_cost = 0.0

    f = open(filename)
    f_csv = csv.reader(f)
    headers = next(f_csv)
    for row in f_csv:
        try:
            nshares = int(row[1])
            price = float(row[2])
            total_cost += nshares * price
        # This catches errors in int() and float() conversions above
        except ValueError:
            print 'Bad row:', row
    f.close()
    return total_cost

# Examples
print portfolio_cost('../../Data/portfolio.csv')
print portfolio_cost('../../Data/missing.csv')

[ Back ]