Data Science and Computing with Python for Pilots and Flight Test Engineers
Functions
Functions are an important element of control flow. We can put pieces of code into functions and thereby remove these lines of code from the main program. In the program, we can then simply call the function with one line of code – perhaps multiple times, if needed repeatedly. This makes the main code of the program clean and easy to read, avoids errors, and if we want to change the function, we can do so in one place (at the function definition) rather than having to track down all of its occurrences in the main code, having to edit each occurrence individually.
The concept for functions transcends computer programming. Functions are ubiquitous in mathematics. Functions are “machines”: they take inputs (called arguments) and they create output, which in a computer program are the return value(s) of the function.
Functions with One Input and One Output Variable
Let us inspect a piece of code below that defines a function, which takes the variable \(x\) as an argument, then either adds 5 or 10 to this variable, and then generates an output, which is the new value of this variable. The following code defines the function:
def add_five_or_ten(x):
""" Function which adds 5 to x, if x is odd; otherwise it adds 10."""
if (x%2==1):
x = x + 5
print("x is odd, so we will add 5.")
else: # we add 10 here on purpose in a cumbersome way, just for illustration:
for i in range(0, 10):
x = x + 1
print("x was even, so have added 10.")
return x # returns this value to the main code which called the function.
Now in the main code we can simply write the following and it looks very clean and brief. We have outsourced all the complexity into the function (we could even put the function into a separate file, if we wanted). And we can call this function now easily multiple times form the main code, as illustrated below.
x = 3 # CHANGE: choose any integer between 0 and 20, and observe result.
# Call the function in the main code, and catch its return value in variable x.
x = add_five_or_ten(x)
# The value of x is now different from what it was initially.
# Call the function again (for the new value of x):
x = add_five_or_ten(x)
print(x)
Functions with Multiple Input and Output Variables
The above example was just a warmup. A function can contain multiple input and output variables. The required syntax is given in the code below, where we illustrate the use of a function called “func” with two input variables and three output variables.
def func(x, y):
u = x + y
v = x - y + 1
w = x * y * 2
return u, v, w
In the main code, we can then call this function with:
r = 5
s = 3
a, b, c = func(r, s)
print(a, b, c)