# Functions - terminology, etc
# Function - a function is basically a set of commands which have
# been grouped together and given a name so that those commands
# can be be executed as a single statement
# Example: A set of commands that will open a file, read in some
# data and return a list. The set of commands is grouped under
# the function name of FillList:
def FillList(filename):
fh = open(filename, 'r')
v = []
while (d = fh.readline()):
v.append(float(d))
return v
# Function call: The command that makes the function execute.
# Example for the function defined above:
vector = FillList('myfile.txt')
# Arguments:
# The data sent to the function for use. The arguments are
# in the parens after the function name, in the function call.
# In the function call above, the function takes a single argument
# 'myfile.txt'. If there was multiple data required, each
# argument would be separated by the next using commas
# Parameters
# The variables in the parens in the function's "def" line.
# The parameters are the variables that will receive the arguments
# which are sent to the function. Parameters are variables
# in the function - they are not able to be used outside of
# the function. In the example above, the function FillList()
# has a single parameter: filename. If a function requires
# multiple pieces of information (i.e. if it will need multiple
# arguments), there would be more than one parameter (each an
# independent variable) and they would be separated by commas.
# Another example:
# A function which has multiple arguments and returns multiple
# values:
# Another example:
# A function which has multiple arguments and returns multiple
# values:
def Stats(filename, max_data_count):
fh = open(filename, 'r')
v = []
cnt = 0
d = fh.readline()
while len(d)>0:
v.append(float(d))
d = fh.readline()
cnt = cnt + 1
s = sum(v)
# Compute the mean
m = s / len(v)
# Compute the standard deviation
t = 0
for x in v:
diff = x - m
t = t + (diff*diff)
sd = math.sqrt(t/len(v))
# return all three values
return s, m, sd
# The main program:
import math
# The associated function call:
s, mean, sd = Stats('datapy.txt', 6)
# Using the returned values:
print('Sum: %f, Mean: %f, SD: %f' % (s, mean, sd))