Functions¶

Applied Review¶

Conditions¶

  • Conditions allow us to execute different chunks of code depending on whether a condition is true or false.
  • The condition syntax is
if condition:
    my_code()
else:
    my_other_code()

Iteration¶

  • Python supports several kinds of iteration structures, which we generally call loops.
  • for loops iterate through elements in a collection
for x in collection:
        do_something_with_x()
  • while loops run until a condition is no longer true
while x > 3:
        do_something()

DRY¶

A fundamental precept of good programming is Don't Repeat Yourself, often abbreviated DRY. Repetition can happen when you want to do one operation (or a slight variant) several times and simply copy and paste your code to achieve that goal.

Copy-pasting is almost always a red flag that you're violating DRY!

Repetition leads to a few problems:

  • Longer, more verbose code
  • Worse readability
    • Others have to spend a lot of time looking through your code to realize you're doing the same thing over and over.
  • Difficulty in updating methodology
    • If you want to change something about the code block you repeated, you have to change it everywhere that code occurs.
    • And this can lead to errors -- manually changing things multiple times is mistake-prone

Functions to the Rescue¶

The best solution to DRY is usually functions.

Functions are code blocks that can be saved. Functions have names, and if they're named well you can easily understand what they're for.

In [1]:
mylist = ['brad', 'ethan']
len(mylist)
Out[1]:
2

len is a function to return the length of a list. Functions that come with Python tend to have short names since they're used so much.

len abstracts away a block of code so we don't have to think about how it works. But what might be inside the len function?

In [2]:
counter = 0
for item in mylist:
    counter = counter + 1
print(counter)
2

The great thing about functions, like len, is that they allow us to avoid rewriting the underlying logic (like the above for loop) every time we want to do a common operation.

Functions in other libraries are often named more verbosely -- which can be helpful since it tells us how to use them.

In [1]:
date_string = '2019-01-01'
date_string
Out[1]:
'2019-01-01'
In [2]:
import datetime as dt
# Convert the date string into a datetime
dt.datetime.strptime(date_string, "%Y-%m-%d")
Out[2]:
datetime.datetime(2019, 1, 1, 0, 0)

datetime's strptime function converts string into a datetime object.

Terminology¶

The most fundamental property of a function -- both in math and in programming -- is that it transforms inputs into outputs.

For example, absolute value is a function. The absolute value of x (in math, often written |x|) is x when x is positive, but (-x) when x is negative.

x f(x)
1 1
2 2
-1 1
-5 5

Python has a built-in version of the absolute value function.

In [5]:
abs(1)
Out[5]:
1
In [6]:
abs(-5)
Out[6]:
5

In the context of functions, inputs are called arguments, and outputs are called return values.

In abs(-5), the function argument is -5 and the return value is 5.

Defining Your Own Functions¶

You've used plenty of functions that others have written for you, but as your Python projects become more complicated you'll want to begin writing your own functions to follow the DRY principle.

In Python, functions are created using two new keywords, def (as in define) and return. The general structure is:

def myfunction(arguments):
    code_block
    return return_value

The return keyword is optional -- your function doesn't have to return a value. It might do something else, like modify a DataFrame.

But if your function produces some kind of output, return is the way to express that.

Let's write a function that doubles a number and call that function double.

In [7]:
def double(number):
    doubled_number = number * 2
    return doubled_number

We can call our new function the same way we would with any function in Python.

In [8]:
double(3)
Out[8]:
6
In [9]:
x = 5
double(x)
Out[9]:
10

double works just the same as abs -- in Python, there's nothing stopping you from building new functions that work as seamlessly as the built-in functions.

Functions can take multiple arguments. We could write a function to return the product of two numbers.

In [10]:
def multiply(x, y):
    product = x * y
    return product
In [11]:
multiply(7, 4)
Out[11]:
28

Note that the names we use for arguments and return values (here x, y, and product) aren't relevant outside the function. We say that they exist only within the scope of the function.

Your Turn¶

The area of a triangle is \begin{equation*} A = \frac{h * b}{2} \end{equation*} where h is the height and b is the length of the base.

Write a function called area that takes arguments h and b and returns the area of a triangle with those dimensions.

More Complex Functions¶

Functions unlock a great deal of power in programming. It's often handy to write functions that handle data manipulation workflows that you do regularly.

Take this data:

In [4]:
data
Out[4]:
{'001': 'Smith Real Estate, Inc.',
 '002': 'Johnson Realty',
 None: 'John Doe Real Estate, LLC'}

Maybe you commonly work with data like this and always:

  1. Filter out rows with missing IDs (keys)
  2. Convert the names to all lowercase so it's consistent.

It's simple to write a function that will do that in a single line for you.

In [5]:
def clean(data):
    # Updating keys and values means we should start with a blank dictionary
    clean_data = {}
    for id, name in data.items():
        # Only keep values where the ID is not missing
        if id is not None:
            # Make the name lowercase
            clean_data[id] = name.lower()
    return clean_data
In [6]:
clean(data)
Out[6]:
{'001': 'smith real estate, inc.', '002': 'johnson realty'}

We can then apply this function to other similarly-structured data.

In [8]:
data2
Out[8]:
{'123': 'Berkshire Hathaway', None: 'Howard Hannah', '321': "Southeby's"}
In [9]:
clean(data2)
Out[9]:
{'123': 'berkshire hathaway', '321': "southeby's"}

There's no limit to how much complexity or code can be put in a function. In software development, it's not uncommon to find functions with hundreds of lines.

Moving lots of logic into functions can help programmers simplify their code -- rather than look at the function logic each time, they can get an idea of what's happening by just seeing the function name.

Named Arguments¶

How does Python know which argument is which when we pass multiple?

For example

In [19]:
def raise_to_power(a, b):
    return a ** b
In [20]:
raise_to_power(2, 3)
Out[20]:
8

It's clear that a was set to 2 and b to 3, because we got 8 (23) as our result.

Why didn't the opposite happen? How did Python know that we didn't mean that b should be 3 and a should be 2?

It's because Python respects the order of arguments; it assigns our arguments to variables in the order that they're passed in.

There's another, more explicit, way to tell Python which value goes with which argument: named arguments, also called keyword arguments.

In [21]:
raise_to_power(a=3, b=1)
Out[21]:
3
In [22]:
raise_to_power(b=1, a=3)
Out[22]:
3

In this format, the syntax argument_name=value specifies which value goes where; the order no longer is important.

If you mix positional and keyword arguments, all the positional ones must come first -- this allows Python to disambiguate how to match the inputs to arguments.

Default Values¶

A handy feature of Python is default argument values -- the ability to set a default for arguments the user may choose not to pass in.

Let's look at an example.

In [23]:
def favorite(number=5):
    return 'My favorite number is ' + str(number)

This function takes an input -- your favorite number -- and prints out a sentence indicating that it's your favorite.

In [24]:
favorite(10)
Out[24]:
'My favorite number is 10'
In [25]:
favorite(number=8)
Out[25]:
'My favorite number is 8'

However, this function also has a default number in case you don't specify one; that's what number=5 means, as one of the arguments.

If we call favorite without specifying an input, it assumes we want number to be 5.

In [26]:
favorite()
Out[26]:
'My favorite number is 5'

This functionality is extremely useful for functions that allow the user to customize certain options -- but don't want the user to have to specify them every time.

A good example is the built-in print function. We've seen it before, but we usually only specify a single argument: an object.

x = 'some string'
print(x)

However, if you consult the documentation, you discover that print allows for optional customizations. We usually pass the first one (named value), but not the others, like sep, end, or flush.

In [13]:
print?
Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file:  a file-like object (stream); defaults to the current sys.stdout.
sep:   string inserted between values, default a space.
end:   string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type:      builtin_function_or_method

Usually, you don't need to specify things like the separator or end value; there are intelligent defaults, so you only need to worry about them in specific scenarios.

Docstrings¶

Just as it's best practice to document your code by using comments, it's good form to notate your functions so others (and you) can quickly learn about them -- what they do, what arguments they take, and what value they return.

In Python, this is typically done using a docstring, an optional but very helpful annotation of a function.

In [28]:
def double(x):
    '''Multiply x by 2 and return the result.'''
    doubled = x * 2
    return doubled

Of course, for a function as simple as the above, you could just figure it out from the code. But as functions grow more complex, this documentation becomes more and more useful.

Docstrings are what you've been seeing if you use the function? syntax. Python fetches that function's docstring and shows it to you.

In [29]:
double?
Signature: double(x)
Docstring: Multiply x by 2 and return the result.
File:      ~/Teaching/intermediate-python-datasci/notebooks/<ipython-input-28-b89ab414a77b>
Type:      function

Your Turn¶

Look at the docstrings of two functions in Python -- you can check out pow and enumerate, for example.

What arguments do these functions take? Do any of them have default values?

Most, though not all, built-in functions have very descriptive docstrings that extensively document inputs, outputs, and functionality.

Here is a great guide to writing well structured and consistent docstrings.

Your Turn¶

  1. Take a look at the below function
def divide(dividend, divisor):
    quotient = dividend / divisor
    return quotient

What variables are the arguments? What variable is the return value?

  1. Write a function cat that takes 3 strings and returns those strings concatenated together with spaces between. E.g. cat('hello', 'friend', 'happy thursday') would return 'hello friend happy thursday'.

  2. Update the function from #2 to give a default value for the third argument. Make the default value a period ('.').

  3. Update the function from #3 to have a docstring. In one sentence, document what the function does.

  4. Update the function from #4 to give a default value for the first argument. Choose any default you like. Does Python allow this? Why?

Lambda Functions¶

Occasionally, you may encounter a Python function that is created without using the def keyword: lambda functions. Lambda functions are one-line functions that do something simple, and are defined using the lambda keyword.

A lambda function to add 5 to an input and return the result would look like

lambda x: x + 5

This means

"For any input x, return that x plus 5."

As you may have noticed, this function doesn't have a name -- we didn't use the define <function_name> syntax. Lambda functions are sometimes called anonymous functions because they don't have names.

Occasionally lambda functions can be handy, but there is no situation where lambda functions are necessary. For this reason, we recommend using named (non-lambda) functions until you've become very comfortable with functions in Python.

Questions¶

Are there any questions before moving on?