Python: Creating a Custom Function

Tutorial Video

Creating a Custom Function

Let’s create a custom function. To start with let’s create one with no input arguments or return statement but one that just prints a statement to the screen.

Python

Note that we use the keyword def to define the function, then we specify the function name, in this case my_function and affix a parenthesis () and then a colon : to the end of this.

Anything that is part of this function is now indented by a [tab] or four spaces. We can then type in some code which we wish this function to carry out. In this case just the inbuilt print command with the string ‘hello’.

Now let us save this Python Script file containing the function. Select File ↓ Save As…

Save it in Documents:

Then create a subfolder called Python Scripts:

And have the file name as:

HTML

The current folder should be the folder the script file was saved in and the script file should display with the file name given.

Importing a Custom Function

In the same folder let’s create a new script file.

Let us add the following line:

Python

Now let’s save this script file as loadingmycustomfunction.py

We can run this script:

This will load the file with the custom function, mycustomfunction.py and from that file import my_function. Note this will only load the function, not execute it.

Executing a Custom Function

Once this custom function is loaded, it may be executed in either the console or in a subsequent line in the loadingmycustomfunction.py script. Note the function must be called by its name followed by parenthesis (). Compare the following:

Python
Python

If we go to console and restart the kernal.

We can now add the line to the script file and run it:

Python

Importing a Custom Function As

It is possible to input a custom function and rename it which is recommended if you are going to call the function multiple times. For example, let’s import it as a two letter abbreviation:

Python

You will be familiar with this when loading modules such as numpy.

Creating a Second Custom Function

It is possible to create multiple functions in a file. For instance, let us create the custom function what_is_the_time this function will print out The time is followed by the time read from the system clock. The first line of the function (line 10) will import the inbuilt function datetime and (line 11) print statement includes the inbuilt function datetime.datetime.now() note how both line 10 and line 11 are indented.

Python

Let’s now have a look at the spacing. It is recommended to encase each function in 2 blank lines (2 blank lines before the function and 2 blank lines after the function).

This makes it very easy to see what code belongs to what function (particularly if the if, elif and else statements are used).

Importing All Custom Functions from a File

It is possible to import multiple functions from a file by manually loading them one by one:

Python

This may be recommended for code readability in some cases, however one can also import all the functions contained within the custom script file using *

Python

After restarting the kernal and rerunning the script file we get:

Local Variable Space

Recall that when we type in the a NumPy command without loading in NumPy we get an error:

Python
NameError: name 'np' is not defined

And if we import numpy before hand, it will work:

Python

If we now go ahead and add a function called give_me_a_number to mycustomfunction.py which uses a command from the NumPy library:

Python

Then call the NumPy library alongside the give_me_a_number function in loadingmycustomfunction.py when we use the give_me_a_number function it will call an error:

Python
NameError: name 'np' is not defined

This is because each function has it’s own local work space which is not impacted by the outside work space. In this example numpy is imported into the outside work space but is not imported into the work space of the function. Amending the function to import numpy as np will overcome this error:

Python

Now if we restart the kernal and run the script file:

Python

It will execute without an error:

In fact, because there is no requirement for NumPy in the main work space. We can only load NumPy within the function only, restart the kernal and the code will still execute:

Input Arguments

As mentioned above the function has it’s own input work space. It is possible to create a function which requires outside input arguments when calling it. These input arguments are input within the parenthesis. For example let us create a function called sum my numbers.

Python
Python

Now lets modify the loadingmycustomfunction.py script to load sum_my_numbers and execute sum_my_numbers:

Note when adding the parenthesis () after a recognised function in this case sum_my_numbers() the input arguments display. In this case let’s input the values 2 and 4.

Python

One can also explicitly specify the input arguments. If one types in the function in the console with an open parenthesis followed by a tab, then the input arguments will be listed:

Python

In this case we can explicitly set num1 and num2

Python

Inputting the input arguments explicitly allows you to input the input arguments in any order:

Python

Input Arguments as Variables

It is possible to assign input arguments to variables existing in the current work space. In this case a and b.

Python

a=3 and b=1 will be converted to num1=3 and num2=1 in the functions own work space.

If we look at both mycustomfunction.py and importingcustomfunction.py below.

Python
Python

When ran we will see that the values of num1 and num2 printed are the original values. i.e. that they are unchanged in the variable explorer.

This is because in the function work space num1=a and num2=b and these are totally independent to num1 and num2 in the main work space.

Functions with if , else if (elif) and else statements

To customfunction.py we can add the following function greeting. This function uses an if, elif and else to give a greeting depending on the time of the day.

Python

Once again look at the spacing. There are two spaces at the top and end of the function. In the if, elif, else loop after the code following each condition there is also a space.

The code belonging to the function is indented by 4 spaces and the code belonging to the if statement of the function is doubly indented i.e. indented by 8 spaces.

If loadingmycustomfunction.py is updated to import and use greeting we get the following. In my case because the hour is 17, it prints Good Afternoon:

Python

The Return Statement

So far only the print command has been used which always prints to the console, irregardless if it is in a function, script or within the console itself. We will now look at the return statement which can be used to return an output of the function and end the function. Let us modify sum_my_numbers in customfunction.py. Instead of printing num3 we will return it as an output.

Python

Let’s now modify loadingmycustomfunction:

Python

If we call the function like before, we will get no output on the console and the variable won’t be saved either. In essence we will have called the function but failed to output it to a variable.

If we run this line in the console however we do get a value output:

Instead we can output it to a variable:

Python

Now the output will display in the variable editor.

Multiple Outputs

Each function can only have one return statement however the return statement can be a multiple element list. For example if we modify customscript.py to get the sum and difference of two numbers:

Python
Python

If we look on the variable explorer we can see that sum_minus is a list with two elements.

It is also possible to explicitly assign each output argument:

Python

This will give two output arguments, which can be seen on the variable editor.

Defining Function and Calling a Function in the Same File

It is also possible to put the function in the same file as the script being executed. In such a case the function must be assigned at the top of the script before it is called. As the function is the same file, there is no need to load the file as the function will be defined when the script is run.

Python

When ran for the first time, we will be asked to specify a file name:

The function will be defined and run creating the output variables which show in the variable editor.

Creating a Unit Convertor

One can use a function to convert from inches to mm for example using the conversion factor 25.4. The following python script can be created unitconvertor.py

Python

Now say for instance, one has measured the size of a door to have a width of 24 inches and height of 78 inches and want to know the size of the door in mm for a shop that only lists its sizes in mm. We can call this function twice in the same script file with the two different inputs height and width to get the converted height and width:

Python

We can run the script file:

When we do so, we will be asked to save the script file and prescribe it a file name. In this case I will use unitconvertor.py

Now the two new dimensions show up on the variable explorer.

One can also modify unitconvertor.py to create multiple other functions. Say for example the following imperial units were all to be converted into mm.

Python

Exercise, make a unit convertor that converts from mm to inches.

Arguments and Keyword Arguments

We can create a custom function that has an undefined number of positional arguments abbreviated args and keyword arguments abbreviated kwargs.

So far we have only used the positional arguments, the args which have to be specified when the function is called and inserted in order before keyword arguments. The keyword arguments have to be specified by assignment of their keyword to a value.

In the function below, we can set the undefined number of args and the kwargs to the variables myargs and mykwargs and we can look at the type of myargs and mykwargs.

Python
('a', 'b', 'c')
<class 'tuple'>
{'kw1': 'd', 'kw': 'e'}
<class 'dict'>

We see that args are a tuple and the keyword arguments are a dictionary.

We can manually specify the args as a list or tuple and the kwargs as a dictionary and input them into the function:

Python
(['a', 'b'], {'kw1': 'c', 'kw2': 'd', 'kw3': 'e'})
<class 'tuple'>
{}
<class 'dict'>

Here you see by default, that the args list and kwargs dictionary are both taken as positional arguments and form a tuple with a list as its 0th index and a dictionary as its second index.

Adding a * in front of the list of args and ** in front of the list of kwargs will unpack these values. Giving the following result

Python
('a', 'b')
<class 'tuple'>
{'kw1': 'c', 'kw2': 'd', 'kw3': 'e'}
<class 'dict'>

Imperial to mm Converter Revisited

Let’s revisit the imperial to mm converter. Before we defined 7 separate functions for inche, hand, foot, yard, step, pace and mile supposing we want to combine these all into a single function. We can instead of having a single input argument, add a positional input argument to be the numeric value of the measurement and a keyword argument to be a string defining the unit. We can do this by use of an if, elif, … , else conditional statements within the function dependent on the string of the second unit.

We can also make the assumption that we are far more likely to convert a measurement in inches into mm than any other imperial unit so we can set the keyword argument to have a default value of inches.

Python
50.8
50.8
3218688.0

In our case, we will print the value of imp2mm(2) in line 36. Here no keyword argument is specified so the default value for the keyword argument is selected and the function hence assumes we want to convert from a unit=’inch’. In line 37 we have specified the keyword argument and have specified the unit=’inch’, so the value yielded is unchanged as inch is the default unit. In line 38 we have however specified the keyword argument, unit=’mile’ so the default value is overriden and the conversion for a mile is given.

Advertisements