Creating custom functions#

Programming for Geoscientists Data Science and Machine Learning for Geoscientists

Functions in Python are blocks of code that will only be executed when called. They look like this:

    def function_name(arg1, arg2, ...):
        # some code to execute
        return  # return some variables, optional

Function names should be descriptive. The arguments are separated by commas and will become local variables within the function. Any object, and any number of objects, can be returned from a function.

Functions have to appear in the code before you execute them:

a = 1
b = 2

# Create a function
def subtract_numbers(a, b):
    return f"{a} - {b} = {a-b}"

# Call the function
print(subtract_numbers(a, b))
print(subtract_numbers(17,5))
print(subtract_numbers(9, 28))
1 - 2 = -1
17 - 5 = 12
9 - 28 = -19

Even though we have variables a and b in the code, the function does not use them unless they are arguments to the function. Variables a and b inside the function are local variables and they only exist there. If we want to use global variables (variables outside of the function), the code will look like this:

a = 10

# Create a function

def add_to_variable_a(b):
    global a  # Make 'a' a global variable
    a += b
    return a

# Call the function

print("a =", add_to_variable_a(2))
print("a =", add_to_variable_a(4))

# Note how variable a changed
a = 12
a = 16

Exercises#


  • Immutable vs Mutable Functions can change the objects (variables) passed to them. Everything depends if an object is mutable. Compare the behaviour of the two functions below, where the one which changes the list is an example of an in-place algorithm:

def double_list1(l):
    for element in l:
        element *= 2

def double_list2(l):
    for i in range(len(l)):
        l[i] *= 2

    
l = [1,2,3]
print("Original list:", l)

double_list1(l)
print("double_list1:", l)

double_list2(l)
print("double_list2:", l)
Original list: [1, 2, 3]
double_list1: [1, 2, 3]
double_list2: [2, 4, 6]

Let us have some fun with mutability. Define a function which takes a list and doubles the elements at the even indices and negates the ones at odd indices. Test it with your input.

HINT use the for i in range(len(l)): structure of the for loop, a different one might not mutate the list.


  • Simple Search Define a function which checks if an element is present in a list and return a boolean value depending on the result. The signature should be def simpleSearch(l, a):.


  • Ah..Interns: Of course Professor Earth agreed to employ Jenny for the summer internship about temperature analysis. Unfortunately she made a little mistake and now the machine reads the digits of each number in the reverse order.

        temp = ['009','679','568','444']

Jenny produced so many measurements that she would not be able to change them manually. You have to help her! In addition she needs to provide a function avgList(l) which will compute the average of temperature reads from a transformed list. Jenny needs you!