Python Functions
A function is a named block of code that you can run whenever you need it. The keyword def introduces a function definition. return sends a value back to the caller.
def mean(values):
return sum(values) / len(values)
print(mean([72, 88, 95, 61]))
print(mean([1.5, 2.5]))
Parameters and default values
A parameter can have a default value. The caller may then leave that argument out.
def normalize(values, scale=1.0):
highest = max(values)
return [v / highest * scale for v in values]
print(normalize([10, 20, 40]))
print(normalize([10, 20, 40], scale=100))
Writing scale=100 in the call is a keyword argument. It makes the call easier to read.
Docstrings
A string on the first line of a function body is its documentation string, or docstring. help() displays it.
def accuracy(correct, total):
"""Return the share of correct predictions, from 0 to 1."""
return correct / total
help(accuracy)
print(accuracy(46, 50))
Returning more than one value
Separate the values with a comma. Python packs them into a tuple, which you can unpack into separate names.
def min_max(values):
return min(values), max(values)
low, high = min_max([72, 88, 95, 61])
print(low, high)
Try it
Write count_above(values, threshold) that returns how many values are greater than the threshold. Test it with count_above([72, 88, 95, 61], 70). The answer is 3.