Here is part of my module: gm.py
def avg_list(list):
sum = 0
for num in list:
sum += num
avg = float(sum)/len(list)
print avg
def median(list):
i = len(list)
if not i%2: # if i divided my 2 has no remainder
return (list[(i/2)-1]+list[i/2])/2.0 # return the value of this block
else:
median = sorted(list)[len(list)/2] # otherwise, when the list is sorted, the index of len(s) / 2 is the middle number.
return median
When I save this as ‘gm.py’ and open a new script page to input the following function:
import gm
def stats(list):
stats = {} # empty dict named stats
stats['average'] = avg_list(list) # Stats(key)[average] = mean of the list of numbers [values]
stats['median'] = median(list) # same for median
return stats
When I run this program and type stats([2,3,4,5,6])… I get an error saying global variable avg_list not defined. I’m not sure if I’m doing the import correctly?
Do I need to do something like… from gm import avg_list() ?
Either reference the functions on the module object:
or import the functions directly into the global namespace:
Note that you should not name a variable
list. This masks the built-inlist()function / type and can cause confusing errors later if you need to use it.You can write
as
I think you should look at the first branch of your
medianfunction. Does the list need to be sorted there too, like in the second branch?Your
avg_listfunction is also masking a built-in function,sum(), which you could use here instead of manually adding:Finally, look at the last line of that function — it’s
printing theavg, butstatsis expecting it toreturntheavg. The two aren’t the same.