def read_csv_to_floats(filename):
'''
Take string parameters as csv filename
Read in and process file, converting all elements to floats.
Return as 2D list (list of lists)
'''
with open(filename) as file:
data_string = file.readlines()
data_floats = []
for line in data_string:
tmp_floats = []
tmp_list = line.split(',')
for item in tmp_list:
tmp_floats.append( float(item) )
data_floats.append(tmp_floats)
return data_floats
import sys
def do_arithmetic(operand1, operator, operand2):
if operator == 'add':
value = operand1 + operand2
elif operator == 'subtract':
value = operand1 - operand2
elif operator == 'multiply':
value = operand1 * operand2
elif operator == 'divide':
value = operand1 / operand2
print(value)
def main():
assert len(sys.argv) == 4, 'Need exactly 3 arguments'
operator = sys.argv[1]
assert operator in ['add', 'subtract', 'multiply', 'divide'], \
'Operator is not one of add, subtract, multiply, or divide: bailing out'
try:
operand1, operand2 = float(sys.argv[2]), float(sys.argv[3])
except ValueError:
print('cannot convert input to a number: bailing out')
return
do_arithmetic(operand1, operator, operand2)
if __name__ == '__main__':
main()
Check that your solution works by trying the different componenets and a few different values.
#!/usr/bin/env python3
import sys
def main():
'''print each input filename and the number of lines in it,
and print the sum of the number of lines'''
filenames = sys.argv[1:]
sum_nlines = 0 #initialize counting variable
if len(filenames) == 0: # no filenames, advise usage
print("Please provide filenames in order to count number of lines")
else:
for f in filenames:
n = count_file(f)
print('%s %d' % (f, n))
sum_nlines += n
print('total: %d' % sum_nlines)
def count_file(filename):
'''count the number of lines in a file'''
f = open(filename,'r')
nlines = len(f.readlines())
f.close()
return(nlines)
if __name__ == '__main__':
main()
If you have used inflammation_mean.py as the basis for this program then you will have a very different solution.