Functions

We use functions in programming to bundle a set of instructions in a self-contained package. A function is a piece of code written to carry out a specific task. Functions are useful when we want to execute a specific task multiple times within our program.

A function typically has two main components:

  1. an input, which can be assigned a default if not specified

  2. an output, which gets return once the code inside the function is finished running

The general structure of a function looks like this:

def task_name(input):
    # task code goes here
    return output 

The input(s) of the function are called parameters.

Built-in Python Functions

Python comes with a wide variety of built-in functions. For example, type() is a function that takes a value or variable name as its input and returns the name of the datatype as the output.

type(100)
int

sum() is another built-in Python function that takes in a list of values and returns the sum. Similarly, len() takes in a list and returns the length of that list.

n_apples = [10,20,30]

print(f"sum: {sum(n_apples)}")
print(f"len: {len(n_apples)}")
sum: 60
len: 3

If you want to learn more about a Python function, you can use the help() function:

help(sum)
Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

How to Define Your Own Function

When defining your own function, here are the steps that you should follow:

  1. Use the keyword def to declare the function and follow this with the function name

  2. Add parameters (inputs) to the function. These go inside the parentheses of the function.

  3. Add statements (instructions/logic) that the function should execute.

  4. End the function with a return statement so that it returns the desired output.

You don’t need to have a return statement for your function to be valid. What happens when your function doesn’t return anything?

def hello():
    print("hello!")

hello()
hello!

Don’t be confused with the function above! It’s printing "hello!" but it’s not returning it.

output = hello()

print(f"Output type: {type(output)}")
hello!
Output type: <class 'NoneType'>

Here’s an example that has two parameters (number_1, number_2) and returns the sum of those two inputs.

def sum_numbers(number_1, number_2):
    total_sum = number_1 + number_2
    return total_sum

x = sum_numbers(10,15)
x
25

Documenting Your Function

When defining your function, it’s very important to include documentation. A function’s documentation is called docstrings. It typically describes the purpose of your function, what computations it performs, and what gets returned. It also provides information on what your inputs should be.

In Python, there are two main styles for writing docstrings. The first style is Google:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Args:
        arg1 (int): Description of arg1
        arg2 (str): Description of arg2

    Returns:
        bool: Description of return value

    """
    return True

The second style is Numpy:

def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    """
    return True

Before building a Python application, it’s a good idea to decide which docstring style you want to use. If your docstrings are short and simple, Google’s style is a great option. If you have long, in-depth docstrings, you may want to opt for the Numpy style. That being said, this is mainly a style preference. Both docstring styles are valid.

Let’s re-write our sum_numbers() function with docstrings using the Google style guide.

def sum_numbers(number_1, number_2):
    """Sums two numbers together. 
    
    Args:
        number_1 (int): first number to be summed
        number_2 (int): second number to be summed
    
    Returns:
        int: sum of number_1 and number_2
    """
    total_sum = number_1 + number_2
    return total_sum

Want to see more examples of Python docstrings in action? Check out the code base of open-source Python packages like pandas and scikit-learn for inspiration.