<jupyter_start><jupyter_text>Programming with Python Creating Functions minutes: 30>  Learning Objectives>> *   Define a function that takes parameters.> *   Return a value from a function.> *   Test and debug a function.> *   Set default values for function parameters.> *   Explain why we should divide programs into small, single-purpose functions.At this point,we've written code to draw some interesting features in our topographical data,loop over all our data files to quickly draw these plots for each of them,and have Python make decisions based on what it sees in our data.But, our code is getting pretty long and complicated;what if we had thousands of datasets,and didn't want to generate a figure for every single one?Commenting out the figure-drawing code is a nuisance.Also, what if we want to use that code again,on a different dataset or at a different point in our program?Cutting and pasting it is going to make our code get very long and very repetitive,very quickly.We'd like a way to package our code so that it is easier to reuse,and Python provides for this by letting us define things called 'functions' -a shorthand way of re-executing longer pieces of code. Import required packages<jupyter_code>import numpy 
import matplotlib.pyplot<jupyter_output><empty_output><jupyter_text>Let's start by defining a function `fahr_to_cel` that converts temperatures from Fahrenheit to degrees. To convert temperatures in degrees Fahrenheit to Celsius, subtract 32 and multiply by .5556 (or 5/9). The function definition opens with the word `def` you need to define a function,which is followed by the name of the functionand a parenthesized list of parameter names.The [body](reference.htmlfunction-body) of the function --- thestatements that are executed when it runs --- is indented below the definition line.When we call the function,the values we pass to it are assigned to those variablesso that we can use them inside the function.Inside the function,we use a [return statement](reference.htmlreturn-statement) to send a result back to whoever asked for it.Let's try running our function.Calling our own function is no different from calling any other function: We've successfully called the function that we defined,and we have access to the value that we returned. Composing FunctionsNow that we've seen how to turn Fahrenheit into Celsius,it's easy to turn Celsius into Kelvin (+ 273.15): What about converting Fahrenheit to Kelvin?We could write out the formula,but we don't need to.Instead,we can [compose](reference.htmlcompose) the two functions we have already created: This is our first taste of how larger programs are built:we define basic operations,then combine them in ever-larger chunks to get the effect we want.Real-life functions will usually be larger than the ones shown here --- typically half a dozen to a few dozen lines --- butthey shouldn't ever be much longer than that,or the next person who reads it won't be able to understand what's going on. Tidying upNow that we know how to wrap bits of code up in functions,we can make our topo analysis easier to read and easier to reuse.First, let's make an `analyze` function that generates our plots:<jupyter_code>def analyze(filename):

    data = numpy.loadtxt(fname=filename, delimiter=',')

    fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0))

    axes1 = fig.add_subplot(1, 3, 1)
    axes2 = fig.add_subplot(1, 3, 2)
    axes3 = fig.add_subplot(1, 3, 3)

    axes1.set_ylabel('average')
    axes1.plot(data.mean(axis=0))

    axes2.set_ylabel('max')
    axes2.plot(data.max(axis=0))

    axes3.set_ylabel('min')
    axes3.plot(data.min(axis=0))

    fig.tight_layout()
    matplotlib.pyplot.show()<jupyter_output><empty_output><jupyter_text>Try it:<jupyter_code>filename ='../../data/topo.asc'
analyze(filename)<jupyter_output><empty_output><jupyter_text>Testing and DocumentingOnce we start putting things in functions so that we can re-use them,we need to start testing that those functions are working correctly.To see how to do this,let's write a function to center a dataset around the mean of that dataset (or in other words, that the mean becomes 0 in the centered datasets, values smaller than the mean become negative, values greater than the mean become positive : We could test this on our actual data,but since we don't know what the values ought to be,it will be hard to tell if the result was correct.Instead,let's use NumPy to create a matrix of 1'sand then center that around its mean: Now, let's write a function to center a dataset around any particular value : Test  That looks right,so let's try `center` on our real data:<jupyter_code>filename ='../../data/topo.asc'
data = numpy.loadtxt(fname=filename, delimiter=',')<jupyter_output><empty_output><jupyter_text>It's hard to tell from the default output whether the result is correct,but there are a few simple tests that will reassure us:<jupyter_code>print('original min, mean, and max are:', data.min(), data.mean(), data.max())
centered = center(data, 0)
print('min, mean, and and max of centered data are:', centered.min(), centered.mean(), centered.max())<jupyter_output><empty_output><jupyter_text>That seems almost right:the original mean was about ca. 3153.6,so the lower bound from zero is now about 3153.6-2565.0293.The mean of the centered data isn't quite zero --- we'll explore why not in the challenges --- but it's pretty close.We can even go further and check that the standard deviation hasn't changed:<jupyter_code>print('std dev before and after:', data.std(), centered.std())<jupyter_output><empty_output><jupyter_text>Those values look the same,but we probably wouldn't notice if they were different in the sixth decimal place.Let's do this instead:<jupyter_code>print('difference in standard deviations before and after:', data.std() - centered.std())<jupyter_output><empty_output><jupyter_text>Again,the difference is very small.It's still possible that our function is wrong,but it seems unlikely enough that we should probably get back to doing our analysis.We have one more task first, though:we should write some [documentation](reference.htmldocumentation) for our functionto remind ourselves later what it's for and how to use it.The usual way to put documentation in software is to add [comments](reference.htmlcomment) like this: There's a better way, though.If the first thing in a function is a string that isn't assigned to a variable,that string is attached to the function as its documentation:<jupyter_code><jupyter_output><empty_output><jupyter_text>This is better because we can now ask Python's built-in help system to show us the documentation for the function: A string like this is called a [docstring](reference.htmldocstring).We don't need to use triple quotes when we write one,but if we do,we can break the string across multiple lines:  Defining DefaultsWe have passed parameters to functions in two ways:directly, as in `type(data)`,and by name, as in `numpy.loadtxt(fname='something.csv', delimiter=',')`.In fact,we can pass the filename to `loadtxt` without the `fname=`: but we still need to say `delimiter=`:What happens if you enter the following statement?   ~~~ {.python} numpy.loadtxt('data/topo.asc', ',') ~~~ To understand what's going on,and make our own functions easier to use,let's re-define our `center` function like this: The key change is that the second parameter is now written `desired=0.0` instead of just `desired`.If we call the function with two arguments,it works as it did before:<jupyter_code>test_data = numpy.zeros((2, 2))
print(center(test_data, 3))<jupyter_output><empty_output><jupyter_text>But we can also now call it with just one parameter,in which case `desired` is automatically assigned the [default value](reference.htmldefault-value) of 0.0:<jupyter_code>more_data = 5 + numpy.zeros((2, 2))
print('data before centering:')
print(more_data)
print('centered data:')
print(center(more_data))<jupyter_output><empty_output><jupyter_text>This is handy:if we usually want a function to work one way,but occasionally need it to do something else,we can allow people to pass a parameter when they need to but provide a default to make the normal case easier.The example below `display` shows how Python matches values to parameters:<jupyter_code>def display(a=1,b=2,c=3):
    print('a:', a,'b: ',b,'c: ', c)

print('no parameters:')
display()
print('one parameter:')
display(55)
print('two parameters:')
display(55, 66)<jupyter_output><empty_output><jupyter_text>As this example shows,parameters are matched up from left to right,and any that haven't been given a value explicitly get their default value.We can override this behavior by naming the value as we pass it in:<jupyter_code>print('only setting the value of c')
display(b=77)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.0785625212560934, 'fraction_numerical': 0.00940936401768507, 'mean_word_length': 5.351331893448524, 'pattern_counts': {'":': 0, '<': 49, '<?xml version=': 0, '>': 56, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '12', 'dir': 'jupyter-structured-clean-dedup', 'id': '127921', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 2522, 'n_tokens_neox': 2386, 'n_words': 1141, 'path': 'lessons/python/07-func.ipynb', 'repo_name': 'csdms/ivy', 'size': '8821'}