forked from dabeaz-course/practical-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpcost.py
More file actions
32 lines (27 loc) · 848 Bytes
/
pcost.py
File metadata and controls
32 lines (27 loc) · 848 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# pcost.py
import csv
def portfolio_cost(filename):
'''
Computes the total cost (shares*price) of a portfolio file
'''
total_cost = 0.0
with open(filename) as f:
rows = csv.reader(f)
headers = next(rows)
for rowno, row in enumerate(rows, start=1):
record = dict(zip(headers, row))
try:
nshares = int(record['shares'])
price = float(record['price'])
total_cost += nshares * price
# This catches errors in int() and float() conversions above
except ValueError:
print(f'Row {rowno}: Bad row: {row}')
return total_cost
import sys
if len(sys.argv) == 2:
filename = sys.argv[1]
else:
filename = input('Enter a filename:')
cost = portfolio_cost(filename)
print('Total cost:', cost)