User defined functions¶

Introduction and general conceptualisation¶

After we learn the most basic and essential data types and structures commonly used in Python, we want to look at the so-called user-defined function (UDF). The usage and the general concept of user-defined functions are identical to the built-in functions of Python that have been introduced before. UDFs allow you to externalise and encapsulate a logical sequence of code statements that marks a specific task repeatedly used under similar conditions. For instance, that could be an often-used calculation or a code fragment used multiple times within your script in more or less the same way.

UDFs are defined as their own self-contained and executable block. Well-programmed UDFs are flexible to varying executing condition over preconfigured parametrisations within the functiondeclaration itself. Thereover UDFs allow you to:

  1. write clean code by externalising and bundling often-used code fragments in only one dedicated code block. This has the advantage that the logic is summarised within the UDF itself. The code is stored at one location, simplifying the code refactoring and maintenance.
  2. expand the pre-defined range of functions provided by Python with your own functions.

Note: functions defined within an object's scope are called methods. Methods differ distinctively in their concept and usage from UDFs since user-defined functions are universally callable, while methods can only be called under the specific object context!

Declaration, definition and usage of UDFs in Python¶

In Python, a user-defined function is declared by the keyword def followed by the <function_name>. A complete and empty UDF body looks like this:

In [1]:
def function_name():
    return

Every UDF in Python consists of 3 main components:

  1. The function's declaration is introduced by def and followed by the individual name of the function.
  2. The parametrisation of the function withhin the () brackets after the function declaration. In the above example, the function is non-parameterized. Hence the brackets are empty. In the following also, examples of parameterized functions are shown.
  3. The function's body is followed by :. The function body must at least contain the return statement. Every function in Python needs to return a value.

After the function is defined, it can be used anywhere within the same programming context by just typing/calling the function's name.

Example: Defining and using a UDF to calculate the volume of a cube¶

As a first and simple example for UDFs, we want to declare and develop a function that calculates the value of a cube step by step. Initially, the function should be pretty simple and return the volume of a cube with a fixed edge length. Since this provides no flexibility, we want to adapt and parametrise the function afterwards so that the volume of any given edge length is calculated and returned.

But one after the other. Generally, the volume $V$ of a cube with the edge length $a$ is calculated by:

$$V = a^3$$

Now we want to implement the above equation within a Python UDF. As it should be as simple as possible at first, the function should return the volume of the cube with a fixed edge length of 3:

In [2]:
def cubes_volume():
    return (3**3)

After successfully declaring and implementing the function, we can directly use it by typing the name of the function followed by (). The function should return the value $27$ since $3^3 = 27$:

In [3]:
cubes_volume()
Out[3]:
27

Awesome, that has worked quite well, and you have defined your first UDF! Now we want to adapt our function so that it calculates the cube's volume to any given edge length. For those purposes, we make use of the concept of parametrisation. Hence we add a parameter a within the () brackets of the functions declaration. Within the function's body, we use this parameter for the volume calculation:

In [4]:
def cubes_volume(a):
    return (a**3)

After we re-declared the function cubes_volume(), we can check it out. Just try a few different edge lengths on your own. The following are some examples:

In [5]:
cubes_volume(3)
Out[5]:
27
In [6]:
cubes_volume(100)
Out[6]:
1000000
In [7]:
cubes_volume(5)
Out[7]:
125

Great! As an additional add-on, we can assign a so-called default value to the function's parameter a. This ensures that the function is still operable even though no value for a is passed:

In [8]:
def cubes_volume(a=3):
    return (a**3)
In [9]:
cubes_volume()
Out[9]:
27
In [10]:
cubes_volume(5)
Out[10]:
125

Exercises¶

Exercise: Write a function that computes Kelvin from Fahrenheit! The function shall be named as fahrenheit_to_kelvin and shall also be parameterised. Kelvin is converted to Fahrenheit by:

$$K = (°F - 32.0) \times \frac{5}{9} + 273.15$$
In [ ]:
### your solution
In [11]:
Show code
def fahrenheit_to_kelvin(F):
    """
    Function to compute Fahrenheit from Kelvin
    """
    
    K = (F - 32.0) * 5/9 + 273.15
    
    return K

Test your function:
$-50\ F$ should yield approximately $228\ K$.

In [12]:
fahrenheit_to_kelvin(-50)
Out[12]:
227.59444444444443

Exercise: Write a function that computes Celsius from Kelvin! The function shall be named as kelvin_to_celsius. This function should be parameterised too. Celsuis is converted to Kelvin by:

$$°C = K - 273.15$$
In [ ]:
### your solution
In [13]:
Show code
def kelvin_to_celsius(K):
    '''
    Function to compute Celsius from Kelvin
    '''
    
    C = K - 273.15
    
    return C

Test your function:
$0\ K$ should yield approximately $-273.15 °C$.

In [14]:
kelvin_to_celsius(0)
Out[14]:
-273.15

Exercise: Write a function that computes Celsius form Fahrenheit! The function shall be named as fahrenheit_to_celsius. This function should be parameterised too. Reuse your above declared functions for this calculation:

In [ ]:
### your solution
Show code
In [15]:
def fahrenheit_to_celsius(F):
    '''
    Function to compute Celsius from Fahrenheit
    '''
    
    K = fahrenheit_to_kelvin(F)
    C = kelvin_to_celsius(K)
    
    return C

Test your function:
$451\ F$ should yield approximately $232\ °C$.

In [16]:
fahrenheit_to_celsius(451)
Out[16]:
232.77777777777777

Citation

The E-Learning project SOGA-Py was developed at the Department of Earth Sciences by Annette Rudolph, Joachim Krois and Kai Hartmann. You can reach us via mail by soga[at]zedat.fu-berlin.de.

Creative Commons License
You may use this project freely under the Creative Commons Attribution-ShareAlike 4.0 International License.

Please cite as follow: Rudolph, A., Krois, J., Hartmann, K. (2023): Statistics and Geodata Analysis using Python (SOGA-Py). Department of Earth Sciences, Freie Universitaet Berlin.