# Function - University of Stirling Functions John R. Woodward Functions 1. A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. 2. As you already know, Python gives you many built-in functions like print(), etc. but you can

also create your own functions. These functions are called user-defined functions. Defining a Function 1. Function blocks begin with the keyword def followed by the function name and parentheses ( ). 2. Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. 3. The first statement of a function can be an optional statement - the documentation string of the function or docstring.

4. The code block within every function starts with a colon (:) and is indented. 5. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. Docstring def add(x, y): """Return the sum of x and y.""" return x + y

help(add) Help on function add in module __main__: add(x, y) Return the sum of x and y. None

Syntax & Example def functionname( parameters ): function_suite return [expression] The following function takes a string as input parameter and prints it on standard screen. def printme( str ): print str return Argument does not need to be string

def printme( str ): print str return printme("cat") printme(5) printme([1,2,3]) Appending a list in a function def changeme( mylist ):

"This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return mylist = [10,20,30]; print "Values outside the function: ", mylist changeme( mylist ); print "Values outside the function: ", mylist

Output Values outside the function: [10, 20, 30] Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]] Reassigning a list in a function def changeme( mylist ): "This changes a passed list into this

function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return mylist = [10,20,30]; print "Values outside the function: ", mylist changeme( mylist ); print "Values outside the function: ", mylist

Output Values outside the function: [10, 20, 30] Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30] Default arguments def printinfo( name, age = 35 ): "This prints passed info into this function" print "Name: ", name print "Age ", age

return; printinfo( age=50, name="miki" ) printinfo( name="miki" ) Default arguments def printinfo( name, age = 35 ): "This prints a passed info Name: miki into this function" print "Name: ", name Age 50 Name: miki

print "Age ", age Age 35 return; printinfo( age=50, name="miki" ) printinfo( name="miki" ) Variable-length arguments def printinfo( arg1, *varArg ): "This prints a variable passed arguments" print "Output is: "

print arg1 for var in varArg: print var return; printinfo( 10 ) printinfo( 70, 60, 50 ) Variable-length arguments def printinfo( arg1, *varArg ): "This prints a variable passed arguments"

print "Output is: " Output print arg1 10 for var in varArg: Output print var 70 return; printinfo( 10 ) 60

printinfo( 70, 60, 50 ) 50 is: is: What would this mean? def printinfo2( arg1, *vartuple, *vartuple2 ): "This prints a variable

passed arguments If your programming langauge did not have this, how could you achieve it? arrays What type is varArg def printinfo( arg1, *varArg ): print "Output is: " print arg1 print type(arg1) print type(varArg)

if (len(varArg)>2): print varArg return; printinfo( 70, 60, 50, 40 ) What type is varArg def printinfo( arg1, *varArg ): print "Output is: " Output is:

print arg1 70 print type(arg1) print type(varArg) if (len(varArg)>2):

40 print varArg return; printinfo( 70, 60, 50, 40 ) Functional Programming In a few weeks we will do a few lectures on functional programming. Anonymous functions will be very useful.

name = John # assigns print name # references Or we can do it directly Print John # we do not name a variable Anonymous Functions 1. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.

2. Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. 3. An anonymous function cannot be a direct call to print because lambda requires an expression Lambda example sum = lambda arg1, arg2: arg1 + arg2; print "Value of total : ",

sum(10,20) print "Value of total : ", sum(20,20) OUTPUT Value of total : 30 Value of total : 40 The return Statement def sum( arg1, arg2 ): total = arg1 + arg2 print "Inside the function : "

print total return total; total = sum( 10, 20 ); print "Outside the function : " print total output

Inside the function : 30 Outside the function : 30 Multiple return statements def max(x1, x2): if x1 > x2:

return x1 else: return x2 None (Null in other languages) def f(): print "in f() now"

f() None (Null in other languages) def f(): print "in f() now" f() in f() now None (Null in other languages)

def f(): print "in f() now" print f() None (Null in other languages) def f(): print "in f() now" print f()

in f() now None Do you return None def f(x): print "you passed in x " + str(x) y = f("argument") print "y = " + str(y) print y==None print type(None)

print type(y) Do you return None def f(x): print "you passed in x " + str(x) you passed in x y = f("argument") argument print "y = " + str(y) y = None

True print y==None print type(None) print type(y) eval On this website you can try Clojure (http://www.tryclj.com/)

eval On this website you can try Python (https://www.pythonanywhere.com/) Python Modules Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code. In a file called

aname.py x = "hi there" def print_func( par ): print "Hello : ", par return In a different file

import aname print aname.x aname.print_func("JOHN") We can now import that file and use it. as

import aname as an print an.x an.print_func("JOHN") as means you can call the module a different name. You will often see import numpy as np Are these the same? def printme( str ): def printme( str ):

print str print str return Are these the same? def printme( str ): def printme( str ): print str print str return Yes, the only difference is one has an explicit return statement and the other one does not.

Which is better programming style. WHY Are these the same? def printme( str ): def printme( str ): print str print str return Are these the same? def printme( str ): def printme( str ): print str

print str return Which is better programming style. WHY??? I would say the left side with explicit return, because you do not look like you forgot it. But not much difference really. Are these the same? def printme( str ): def printme( str ): print str print str

return return None Which is better programming style. WHY??? I would say the left side with explicit return, because you do not look like you forgot it. But not much difference really. and None are different

name = "" print name print type(name) name = None print name print type(name)

and None are different name = "" print name print type(name)

name = None None print name print type(name) () and None are different tupleNames = ("John", "David") print tupleNames print type(tupleNames) tupleNames = ()

print tupleNames print type(tupleNames) tupleNames = None print tupleNames print type(tupleNames) () and None are different tupleNames = ("John", "David") print tupleNames ('John', 'David') print type(tupleNames)

tupleNames = () () print tupleNames print type(tupleNames) tupleNames = None None print tupleNames print type(tupleNames)

A SINGLE TUPLE tupleNames = ("John") print tupleNames print type(tupleNames) A SINGLE TUPLE tupleNames = ("John") print tupleNames print type(tupleNames) OUTPUT

John Type of Single List listNames = ["John", "David"] print listNames print type(listNames) listNames = ["John"] print listNames print type(listNames)

Type of Single List listNames = ["John", "David"] print listNames print type(listNames)['John', 'David'] listNames = ["John"] ['John'] print listNames

print type(listNames)