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
(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 ]