# 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[2] 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[2] 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)

## Recently Viewed Presentations

• We will return to this principle in Chapter 6 and Chapter 8 where we will derive a formula for the cardinality of the union of . n. sets, where . n. is a positive integer. U. A. B. Venn Diagram...
• For strict dominance (with or without dominance by mixed strategies), both can be solved in polynomial time due to path-independence Check if any strategy is dominated, remove it, repeat For weak dominance, both questions are NP-hard (even when all utilities...
• raised heel truss (aka, energy truss) Ceilings with Attics, Cont'd. Section R402.2.1. If insulation is full height uncompressed over exterior wall top plate, covering 100% of ceiling area. R-30 complies where R-38 is required. R-38 complies where R-49 is required....
• Pseudocode is an informal tool that you can use to plan out your algorithms. As you begin to write more complex code, it can be hard to keep an entire program in your head before coding it. Think of pseudocode...
• Agenda: Objective Description of System Model and Modeling Process Example Problem Current and Future Work Objective: Build realistic virtual bullet/barrel models to: accurately calculate the dynamic performance of bullet and barrel calculate the effects of model variations on interior and...
• Domain Sharding Yslow Rules Reduce DNS Lookups Split Components Across Domains Use Cookie-Free Domains for Components PageSpeed Rules: Parallelize downloads across hostnames Minimize DNS lookups Serve static content from a cookieless domain What I do I use two or three...
• A boy who is 5 ft. tall cast a shadow that is 12 ft long. At the same time, a building nearby cast a shadow that is 72 ft long. How tall is the building? Draw a picture! ? 72...
• Hidden audience for most of the prompts . Some prompts - audience is given ... Song lyrics work well on the SOL! A related anecdote (the beginning of your focus story) If you start with an anecdote, you should come...