Information

Section: Functions
Goal: Understand how functions are built in Python.
Time needed: 10 min
Prerequisites: Curiosity

Functions

Credits: Institute of Maritime Logistics – Hamburg University of Technology

1 Basics

In programming, functions are a mechanism to allow code to be re-used so that complex programs can be built up out of simpler parts.

This is the basic syntax of a function:

def funcname(arg1, arg2,... argN):
    ''' Document String'''
    statements
    return <value>```

Read the above syntax as: A function by name “funcname” is defined, which accepts arguments “arg1,arg2,….argN”. The function has an explanatory text that is ‘’’Document String’’’. When the function is called, the statement is executed and thereafter the function returns a “value”.

Return values are optional (by default every function returns None if no return statement is executed).

Now we define a first function:

def firstfunc():
    print("Hello Jack.")
    print("Jack, how are you?")
firstfunc() # execute the function
Hello Jack.
Jack, how are you?

firstfunc() addresses the message to Jack every time. We can rewrite our function firstfunc() to accept arguments which will store the name and then prints respective to that accepted name. To do so, add an argument within the function as shown.

def firstfunc(username):
    print("Hello %s." % username)
    print(username + ',' ,"how are you?")
myname = 'Sally' # or use your own name

Now the variable is passed to the function:

firstfunc(myname)
Hello Sally.
Sally, how are you?

2 Return Statement

When the function results in some value and that value has to be stored in a variable or needs to be sent back or returned for further operation to the main algorithm, a return statement is used.

def times(x,y):
    z = x*y
    return z

The above defined times( ) function accepts two arguments and return the variable z which contains the result of the product of the two arguments

c = times(4,5)
c
20

The value of z is stored in variable c and can be used for further operations.

Instead of declaring another variable the entire statement itself can be used in the return statement as shown.

def times(x,y):
    '''This multiplies the two input arguments'''
    return x*y
c = times(4,5)
c
20

Since the times( ) is now defined, we can document it as shown above. This document is returned whenever times( ) function is called under help( ) function.

help(times)
Help on function times in module __main__:

times(x, y)
    This multiplies the two input arguments

3 Default arguments

When an argument of a function is common in majority of the cases this can be specified with a default value. This is also called an implicit argument.

def implicitadd(x,y=3,z=0):
    print("%d + %d + %d = %d"%(x,y,z,x+y+z))
    return x+y+z

implicitadd( ) is a function that accepts up to three arguments, but most of the time, the first argument needs to be added just by 3. Hence the second argument is assigned the value 3 and the third argument is zero. Here the last two arguments are default arguments.

Now if the second argument is not defined when calling the implicitadd( ) function, it then is considered as 3.

implicitadd(4)
4 + 3 + 0 = 7
7

However we can call the same function with two or three arguments. A useful feature is to explicitly name the argument values being passed into the function. This gives great flexibility in how to call a function with optional arguments. All of the following are valid:

implicitadd(4,4)
implicitadd(4,5,6)
implicitadd(4,z=7)
implicitadd(2,y=1,z=9)
implicitadd(x=1)
4 + 4 + 0 = 8
4 + 5 + 6 = 15
4 + 3 + 7 = 14
2 + 1 + 9 = 12
1 + 3 + 0 = 4
4

4 Any number of arguments

If the number of arguments that is to be accepted by a function is not known then a asterisk symbol is used before the name of the argument to hold the remainder of the arguments. The following function requires at least one argument but can have many more.

def add_n(first,*args):
    "return the sum of one or more numbers"
    reslist = [first] + [value for value in args]
    print(reslist)
    return sum(reslist)

The above function defines a list of all of the arguments, prints the list and returns the sum of all of the arguments.

add_n(1,2,3,4,5)
[1, 2, 3, 4, 5]
15
add_n(6.5)
[6.5]
6.5

Arbitrary numbers of named arguments can also be accepted using **. When the function is called all of the additional named arguments are provided in a dictionary

def namedArgs(**names):
    'print the named arguments'
    # names is a dictionary of keyword : value
    print("  ".join(name+"="+str(value) 
                    for name,value in names.items()))

namedArgs(x = 3*4,animal = 'mouse')
x=12  animal=mouse

5 Lambda Functions

These are small functions which are not defined with any name and carry a single expression whose result is returned. Lambda functions are useful when operating with lists. These function are defined by the keyword lambda followed by the variables, a colon and the respective expression.

z = lambda x: x * x
z(8)
64