Functions¶

author: Parin Chaipunya affil: KMUTT

Functions¶

A function in python accepts a set of inputs (possibly empty) and uses them to produce outputs (again, possibly empty). A function is usually use when one wants to operate a similar process

A function is created following the following structure.

def function_name(input_1,...,input_n):
    <tasks>
    return output_1,...,output_m

If a funtion has no input, we leave the parenthesis after function_name empty. Likewise, if a function has no output, the line return ... is left out.

Example¶

Let us define a function that takes two inputs x1 and x2, then output two outputs. The first output y1 is the sum x1 + x2, and the second output y2 is the difference x1 - x2.

In [1]:
def sum_and_diff(x1, x2):
    y1 = x1 + x2
    y2 = x1 - x2
    return y1, y2

Next, we show how a funtion could be called.

In [2]:
Sum, Diff = sum_and_diff(5,2)
print(f"sum = {Sum}, diff = {Diff}")
sum = 7, diff = 3

Example¶

We now give an example of a function that requires no input.

In [3]:
def split_line():
    print(f"{20*"-"}")

Now, when the above function split_line is called, even it takes no inputs, we still need the empty parentheses () at the end of the function. The following code block illustrates the calling of such a function.

In [4]:
for i in range(10):
    split_line()
    print(f"i = {i}:  i^2 = {i**2}")
split_line()
--------------------
i = 0:  i^2 = 0
--------------------
i = 1:  i^2 = 1
--------------------
i = 2:  i^2 = 4
--------------------
i = 3:  i^2 = 9
--------------------
i = 4:  i^2 = 16
--------------------
i = 5:  i^2 = 25
--------------------
i = 6:  i^2 = 36
--------------------
i = 7:  i^2 = 49
--------------------
i = 8:  i^2 = 64
--------------------
i = 9:  i^2 = 81
--------------------

Example¶

This example shows a function that has no output.

In [5]:
def mult_table(a):
    split_line()
    for k in range(1,13):
        print(f"{a}*{k}\t=\t{a*k}")
    split_line()
In [9]:
mult_table(7)
--------------------
7*1	=	7
7*2	=	14
7*3	=	21
7*4	=	28
7*5	=	35
7*6	=	42
7*7	=	49
7*8	=	56
7*9	=	63
7*10	=	70
7*11	=	77
7*12	=	84
--------------------

Example¶

Let us consider a function that is more elaborated.

We shall construct a function that verify whether the two matrices $A$ and $B$ can by multiplied.
If the product $AB$ is defined, the the function outputs the product.
Otherwise, outputs a np.nan (which means not-a-number).

In [10]:
import numpy as np
In [11]:
# In the following function, the input verb = "" means this input is default to "" (empty string).
# If we do not explicitly input verb, then this value will be used.
def mult_verif(A, B, verb = ""):
    """
    verb is the verbose level.
    verb = "verbose" indicates to print the output.
    """
    col_A = A.shape[1]
    row_B = B.shape[0]
    if col_A == row_B:
        if verb == "verbose":
            print(f"The product AB is defined. The output is the product.")
        return A @ B
    else:
        if verb == "verbose":
            print(f"The product AB is not defined. The output is `Not-a-Number`.")
        return np.nan
In [12]:
A = np.random.randint(-10, 11, (3, 6))
B = np.random.randint(-10, 11, (4, 5))
C = np.random.randint(-10, 11, (6, 5))
In [13]:
Z1 = mult_verif(A, B)
print(Z1)
nan
In [14]:
Z1 = mult_verif(A, B, verb = "verbose")
The product AB is not defined. The output is `Not-a-Number`.
In [15]:
Z2 = mult_verif(A, C, verb = "verbose")
print(f"Z2 =\n{Z2}")
The product AB is defined. The output is the product.
Z2 =
[[  47   65   66   92  -75]
 [ -43 -202 -195  -60  -33]
 [  58   22   27   62  -99]]

Lambda¶

There is an alternative way to quickly define a function in python, which is known as lambda. It is usually used for functions that are not complicate and could be completed within a line of code.

It follows the structure below.

function_name = lambda input_1,...,input_n: (output_1,...,output_m)

Example¶

Let's use lambda to define the sum of 4 numbers.

In [16]:
SUM = lambda x1, x2, x3, x4: x1 + x2 + x3 + x4
SUM(1, 3, 5, 7)
Out[16]:
16

Example¶

The sum_and_diff function above could be easily rewritten with lambda.

In [17]:
SUM_AND_DIFF = lambda x, y: (x + y, x - y)
Sum, Diff = SUM_AND_DIFF(10, 4)
print(f"Sum = {Sum}, Diff = {Diff}")
Sum = 14, Diff = 6