Mathematics, Sciences, and Technologies

Python for Scientists 1-8: Self-defined Functions

,

Making Our Own Functions

In this tutorial, we talked about the advantages of using functions and introduced some common built-in functions. Many curious readers will wonder whether it is possible for us to write our own functions for other purposes. In fact, it is much needed and every programming language, including Python, allows us to do so. The most general way to create a self-defined function in Python is to use the def keyword, followed by the name of the supposed function and the input arguments in a pair of brackets. Using the temperature conversion exercise in this tutorial as an example, we may write

def temp_C_to_F(temp_C):
temp_F = 9/5*temp_C + 32
return(temp_F)
old_temp = 25
new_temp = temp_C_to_F(old_temp)
print("Temperature Conversion Result:", new_temp, "degree F")

This function temp_C_to_F accepts an input with the dummy name temp_C, and it will read the provided value at that position when the function is called (a positional argument). Notice that we have plugged in old_temp, which can have a different name from the dummy one, and the function will use old_temp in place of temp_C during its execution. Inside the function, we calculate temp_F, return this value as the output, and at the same time exit from it. Then, temp_C_to_F(old_temp) will receive the output result, and it is assigned to new_temp.

In general, the variables in a function are local, which means that their scope is only within the function and will not have any effect or interaction outside it. To illustrate this, we can write

x = 3
def some_func(x):
x = 5
return(x)
y = some_func(x)
print(f"x = {x}, y = {y}")

This should give x = 3, y = 5. (Think about it!)

Keyword Arguments

Compared to positional arguments as described above, sometimes we may utilize keyword arguments, which take parameters by name and hence are more specific, in the form of <argument_name>=<variable>. Below we borrow the calculation of BMI (\( \text{height} / \text{weight}^2 \)) as an example:

def calculate_BMI(height, weight):
BMI = weight / height**2
return(BMI)
YJ_height = 1.70
YJ_weight = 74
print(f"Height: {YJ_height} m, Weight: {YJ_weight} kg")
print("BMI:", round(calculate_BMI(height=YJ_height, weight=YJ_weight),1))

This produces

Height: 1.7 m, Weight: 74 kg
BMI: 25.6

In the code above, when we invoke the function, we associate and read the input variables according to the names of the parameters indicated at the start of the function. It is also possible to just use the old positional argument method, i.e. just write calculate_BMI(YJ_height, YJ_weight).

Default Values

It is also convenient to supply default values to the function arguments so that we may omit them when calling the function (if it is a very common assumption). It can be given at the beginning of the function in the form of <parameter>=<default>. Using the same example, if we write

def calculate_BMI(height, weight=60):
BMI = weight / height**2
return(BMI)
print(calculate_BMI(1.75))
print(calculate_BMI(1.75,75))

then it will output 19.59... and 24.48..., where the first one uses the default weight of 60 kg while the second one accepts the explicit input of 75 kg and overwrites the default value during computation. Also, be aware that in the definition of the function, default arguments must come after the usual ones. So, an error will arise if we write something like def calculate_BMI(height=180, weight): instead.

Docstring

It is always helpful to describe what a defined function does for readability and maintenance. To do so, we add a docstring after the definition with a pair of three apostrophes '''. For example, a possible description for the calculate_BMI function above may be

def calculate_BMI(height, weight):
'''
Calculates the Body Mass Index (BMI) of a person:
Inputs: height (in meters), weight (in kg);
Output: BMI, which is equal to weight divided by height squared.
'''
BMI = weight / height**2
return(BMI)

Lambda Functions

A really handy shortcut to define a simple function is to use the lambda syntax. It will be clearer if we just look at an actual example:

f = lambda x: x**2 - 1
y = f(2)
print(y)

It is very much like a mathematical function. Here we indicate the name of the input dummy variable after lambda, and after the colon we write down how to evaluate the corresponding output. This function is named f and the value of f(2) is just \( 2^2 -1 = 3\).

Exercise

Write a Python function to convert the unit of wind speed from knots to km/h. (\(1\) knot is \(1.852\) km/h), with a default value of \( 80 \) knots. Use this to convert \( 64 \) knots (the threshold of a hurricane intensity) to km/h.

Suggested Solution
def kts_to_kmh(kts=80):
kmh = kts * 1.852
return(kmh)
default_kmh = kts_to_kmh()
hurricane_kmh = kts_to_kmh(64)
print(f"Default output is {default_kmh:.1f} km/h.")
print(f"A hurricane is above {hurricane_kmh:.1f} km/h.")

This should give something like

Default output is 148.2 km/h.
A hurricane is above 118.5 km/h.

Leave a Reply

I’m Benjamin

Welcome to my Mathematical World! Here you can find posts and tutorials related to applied topics like Linear Algebra, Calculus, Differential Equations, and Programming. Feel free to leave comments and suggestions!