How to Create User-Defined Functions in Python
By: Rod Castor
Tags: Programming, Python, Data Science, Towards Data Science, Data Analysis

How to Create User-Defined Functions in Python

Up your Python game by defining your own functions

Have you ever thought, “I wish Python had a function that did ________.” Fill in the blank. If so, I have great news! Python gives you the ability to create your own custom functions. There are a few things you need to understand, but it’s not that hard to do. So let’s get started.

Custom functions are a great way to nicely package reusable blocks of code. At the most basic level, a custom function requires only five components:

Use the def keyword to begin the function definition. Name your function. Supply one or more parameters. Actually parameters are optional, but the parentheses are not. Followed by a colon. Enter lines of code that make your function do whatever it does. Enter the code where the # logic here is shown in the sample code below. Use the return keyword at the end of the function to return the output. This is also optional. If omitted, the function will return None.

As you can see, the bare bones of a function are simple. Let’s stop playing with the theoretical though and create an actual function.

The Function Name

Every function needs a name. Otherwise, you have no way to reference it in your code when you need to use it. Name your function something intuitive. If the purpose of your function is to sum all the numbers you send into it via the parameter list, name it add_nums() or sum_the_numbers(). Do not name it s() or function1(). These last two are poor choices. Remember, code is read by humans.

Also, the function name must be followed by a set of parentheses. If you don’t need any parameters, the parentheses will be empty, but they must present. Then finish the definition line with a colon. The colon indicates any indented lines below this one are part of the function.

Parameters

Once you name your function, decide the required parameters. Parameters, or arguments, are used to pass pertinent data to your function. How many numbers can the function add together? If no parameters are supplied, will default values be used? What’s the order of the arguments?

Parameters are inserted between the parentheses following the function name. They are separated by commas. Again, use intuitive names so you can easily recall the purpose of each parameter.

If our function will only add two numbers, we can create two parameters, num1 and num2. If we change the function to add three numbers, we can add a third parameter, num3.

If you choose to assign default values for the parameters, just replace the current parameter names with num1=0 and num2=0. The 0 should be replaced by whatever default value you want to assign.

Typically, when you execute a function, you’ll call it using a line of code similar to sum_the_numbers (5, 3). By supplying default values, you can omit one or more of the parameters from the execution line of code, and the function will still run, only using the default values.

Logic

Now let’s add some logic to the function. This is what makes the function add the numbers. This section may be short if you are performing a simple task, like adding two numbers together. Or you could have hundreds of lines of code in this portion for a more complex undertaking. Remember, all lines of code included as part of the function must be indented like the total = num1 + num2 line below.

Return a value

Now that your code has completed its prescribed work, you may or maybe not need to return a value to the process that called your function. If you do not need to return a value, you may omit the return statement. However, in this example function, we need to return the sum. The line is return total.

The return statement sends the value stored in total back to the section of code where this function was executed. You will usually have a variable present to store the returned value. For example, summation = sum_the_numbers (5, 3). The value returned by the function will be stored in the summation variable. Now that we have all the necessary components for our function to succeed, let see how we execute it in a code segment.

Executing the Function

Whenever we execute a user-defined function, we use the name of the function with any required parameters. If the function returns a value, we usually will do something with its output. We may print it, store it in a variable, or send it into another function. Assuming we are going to store the output in a variable, our function execution may look something like the code below.

If we choose to print the returned value straight to the screen, we can use this code instead.

Remember, when you call your function the arguments must be supplied in the same order you’ve listed them in the function definition, num1 followed by num2. However, if you’ve forgotten the order you can change it up as long as you specify the argument keywords when executing the function. When using argument keywords, the command will look similar to sum_the_numbers (num2=5, num1=10).

An Indeterminate Number of Parameters

I’m sure you can already see an issue with our design. Every time we wish to add more numbers, we are required to add another parameter. But there is a way to handle an endless number of parameters in your function. Instead of listing each parameter name between the parentheses in the function definition, use the *args technique.

When an * proceeds a parameter name, it indicates any number of parameters may be passed into the function. This will create a list of the parameter values. You simply unpack the args list in the function. This small change in our function has made it much more versatile.

Putting it all Together

Often, the user-defined function and the code executing it are in the same Python script. In our example, the whole script would look like this one.

Standard user-defined functions are straight forward to use, but a very powerful tool for a developer. Of course, user-defined functions do not stop with this standard approach. If you were buying something online or from a late-night infomercial, you’d expect to get even more for your $19.95. The same is true with user-defined functions.

Anonymous Functions

If you like the standard user-defined function, you’ll love anonymous user-defined functions. These functions are written inline, where you need them, without a name, and without proper definition syntax. These functions are also referred to as comprehensions or lambda functions.

For this example, pretend our scenario is the same as above. We need a function capable of add two numbers together. Instead of our sum_the_numbers function, we can use a lambda function.

Lambda is the Python keyword used to define these functions instead of def. Therefore, they are often referred to as lambda functions.

In this example of our lambda function, we defined the variable answers as the function itself. Then we simply pass in the needed parameters when we refer to the variable name. The result is an anonymous function disguised as a dynamic variable.

In short, the syntax for anonymous functions is lambda argument_list: expression.

Let’s take our example one step further and pretend the scenario begins with a list of numbers. We need to create a new list of numbers by squaring every number from our first list. We could create a standard user-defined function to accomplish this as we did above. But instead, we decide to use an anonymous function.

In order to iterate through the list, we use Python’s map function. The map function takes two arguments. The first one is a function. In this case, it will be an anonymous function. The second parameter is some iterable data, like the list of numbers we want to square. The map function will take each item in the iterable, run it through the specified function, and append the output to a new iterable data structure.

The list() function in this code converted the map function’s default iterable output, a map object, to a Python list. List’s are much easier to use throughout the rest of our code.

Again, you can see our lambda code is relatively short compared to the standard approach used below.

Conclusion

Commit the time necessary to learn how to implement user-defined functions in Python. They are powerful. They create reusable blocks of code. They help organize your code. And they are absolutely necessary if you begin using object-oriented programming techniques. User-defined functions are a necessary tool in the modern developer’s repertoire.