Functions in Python¶
What is a function?¶
A function is a block of organised, contained, reusable code. You can imagine using the same block of code, copying and pasting is again and again in your script. What are the chances that in one of those copy and pastes you’ll make a mistake - almost 100%! One of the basic principles in good programming is “do not to repeat yourself” both to avoid mistakes, but also to make code more human readable. Functions allow you to wrap up code into a package that you can use again and again or allow you to use other people’s work to make the job quicker. During the course so far, we’ve already showcased a number of functions, like the print() function. We have also used methods which are functions that are tied to a specific object instance, like [].append().
Before we get into creating your own functions, let’s get a better handle on the structure of functions in python. The general framework of a function is:
def function_name(*args, **kwargs):
outdata = some actions
return outdata
In human speak. The def keyword lets python know you’re creating a function named function_name, which takes as inputs some args and kwargs. An arg is a positional argument, who’s value is defined by the position in the function call, so in this fictional function call:
new_val = function_name(1, 2, trend_type=3)
1 is the first arg, 2 is the second arg. 3 on the other hand is a kwarg or keyword argument; the value of this argument is defined by the keyword trend_type. Following the : in the function definition, there is some indented code that typically does some action and creates a new variable. The end of the function is typically marked by the return keyword. This tells python to create a variable (new_val) and point it to the object that was defined as outdata inside the function. We need to return the object of outdata because as a general rule variables created outside a function are not accessible inside a function unless they are passed in as arguments, and those created inside a function are only accessible outside the function if they are explicitly passed out of the function by the keyword return.
Understanding function documentation¶
There are heaps of already developed functions that probably do almost exactly what you need to do, but in order to use them you need to understand what an existing function does and it’s quirks. The best source of knowledge for this is the function documentation. It can take a bit of time to get good at interpreting documentation, so let’s make a start of it. To start we’ll look at the the built in function to enumerate iterables enumerate(). Original documentation is here, but it is included here as well:
enumerate(iterable, start=0)
Return an enumerate object. iterable must be a sequence, an iterator, or some other object which supports iteration. The __next__() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over iterable.
Let’s look at what the first line of the documentation enumerate(iterable, start=0) is telling us. First enumerate can take up to two arguments (iterable and start), second we need to pass at least one argument (iterable) as it has no default value (it isn’t equal to anything), and third that if we do not pass a value for start it will be set equal to 0.
The body of the text explains what the function does (creates an object, which for our purposes can be converted to a list of tuples that contain a number, starting from start) It also gives more details on the arguments (in this case that iterable, must be some object that supports iteration). So armed with this knowledge are you surprised by the result of:
In [1]: my_list = ['a','b','c']
# remember the list() here is just being used to get away from the unnecessary
# complexity of the enumerate object
In [2]: list(enumerate(my_list, start=10)) # FYI the space after the comma and no spaces between the '=' is pep8 standard
Out[2]: [(10, 'a'), (11, 'b'), (12, 'c')]
# above we passed the arguments as show in the documentation
# we can also pass everything as kwargs in any order we choose
In [3]: list(enumerate(iterable=my_list, start=10))