Upload
clemence-hunt
View
219
Download
2
Embed Size (px)
Citation preview
Chapter 12-13 Chapter 12-13 Function BasicsFunction Basics
CSC1310 Fall 2009CSC1310 Fall 2009
FunctionFunction
In simple terms, a function function (subroutine, (subroutine, procedure)procedure) is a package of code (a set of a set of statementsstatements) that can be called repeatedly with different inputs (different inputs (parametersparameters)) and outputsoutputs each time.
In Python, function is an objectan object which is recorded explicitly at program execution time.
Why Use Function?Why Use Function?
1.1. Code Reuse:Code Reuse: Functions allows us to group and generalize code to be used arbitrarily many times after it is defined.
2.2. Procedural decomposition:Procedural decomposition: Functions also provide a tool for splitting systems into pieces that have a well-defined role (one function for each subtask).
def Statementdef Statement The defdef statement creates a function object and
assigns it to a name. General format:def <name> (arg1,arg2, … argN):def <name> (arg1,arg2, … argN):
<statements><statements> return <value>return <value> Python executes bodybody (statement block) each time
the function is called. The argument names will be assigned with the
objects passed in the parenthesis at the point of a at the point of a callcall.
returnreturn ends function call and sends a result back to a caller.
def Runs at Runtimedef Runs at Runtime The defdef is true executable statement:
Creates and assigns a new function object to a name at a runtime
It is a statement: it can be even nested.
>>>k=int(raw_input())>>>if k==1: def func(): print ”One” else: def func(): print “Not one”>>>print func() The defdef is like an = statement.>>>othername=func>>print othername()
Function ExampleFunction Example
DefinitionDefinition (def) creates a function Call Call – an expression to run the function’s body
>>>def pow(x,y): value=x+y return value
>>>print pow(2,3)
>>>print pow(‘abc’,’345’) # functions are typelesstypeless
PolymorphismPolymorphism
PolymorphismPolymorphism is a type-dependent behavior: the meaning of operations depends on the objects being operated upon.
As long as objects support the expected protocol (interfaceinterface), they can be processed by the function (expected methods and operators, compatible with function’s logic).
If objects do not support interfacedo not support interface, Python raises an exception automatically.
Python vs Java, C++: your code is not supposedis not supposed to care about specific data types (we code to object code to object interfacesinterfaces, not data type.)
Example: Intersecting Example: Intersecting SequencesSequences>>>def intersect(x,y):
res=[] # local variablelocal variable
for z in x:
if z in y: res.append(z)
return res You can run code as many times as you want. It is general to work on any two sequences. You need to change code only in one place. It can be imported and reused by any other program.
Intersecting Sequences: Intersecting Sequences: CallCall>>>s1,s2=‘Wiki’, ’wiki’
>>>intersect(s1,s2)
>>>print intersect([1,2,3], (1,4))
>>>print intersect([1,2,3], (4))
Scope RulesScope Rules
NamespaceNamespace is the place where names live The location of name’s assignment defines the
scopescope of the name visibility. Names defined inside a def def can be seen only by the
code inside the defdef. Names defined inside a defdef not clash with variables
outside the defdef, even if the same name is used elsewhere.
Scope BasicScope Basic The enclosing module is a global scope. The global scope spans a single file only. Each call to a function is a new local scope. Assigned names are local, unless declared global. All names are either local, or global, or built-ins. Name resolution: the LEGB Rule: LEGB Rule: name references
search at most at fours scopes: Local Enclosing functions (if any) Global Built-in.
global Statementglobal Statement Global names must be declared only if used in a function. Global names may be referenced in a function without
being declared. global <name1,name2,…nameN>global <name1,name2,…nameN>
>>>X=88
>>>def func():
global X
X=99
>>>func()
>>>print X
Nested FunctionsNested Functions Within a function:
Assignment: X=valueAssignment: X=value creates or changes name x in the current local scope by default. If X is declared global global within a function, it creates or changes X in the enclosing module’s scope instead.
Reference: XReference: X looks for a name in the current local scope (function), then in the local scopes of all lexically enclosing functions from inner to outer (if any), then in the current global scope (the module file), and finally in built-in scope. globalglobal declaration makes the search begin in the global scope instead.
Passing ArgumentsPassing Arguments Arguments are passed by automatically assigning objects to a
local names. Assigning to arguments’ names inside a function doesn’t affect
the caller (“by value”)(“by value”). Changing a mutable object argument in a function may impact a
caller (“by pointer”)(“by pointer”).
>>>def change(x, y):
x=2; y[0]=‘hi’
>>>x=1;L=[1,’a’]
>>>change(x,L)
>>>print x,L
Avoiding Mutable Arguments Avoiding Mutable Arguments ChangesChanges We can copy the list at the point of the call>>>L=[1,’a’]>>>change(x,L[:]L[:]) # pass a copy We can copy list within the function itself, if we never want
to change passed-in objects.>>>def change(x, y): y=y[:] x=2; y[0]=‘hi’ Both variants above only prevent changes from impacting
a caller. We can convert to immutable objects.>>>L=[1,’a’]>>>change(x,tuple(L)tuple(L)) # pass a tuple
Simulating Output Simulating Output ParametersParameters returnreturn sends back any sort of object It could return multiple values, by packaging them in
tuple.>>>def swap(x,y): y=x+y x=y-x y=y-x return x,y>>>a,b=swap(3,5)>>>print a,b
Special Argument Matching Special Argument Matching ModesModes Positional: Positional: matched left to right. Keywords:Keywords: matched by the argument name. Callers
can specify which argument is to receive a value by specifying the argument’s name in the call with a name=valuename=value syntax.
Varargs:Varargs: catch unmatched positional or keyword arguments. Function can use special arguments preceded with a ** characters to collect arbitrarily extra arguments.
Defaults:Defaults: specify values for arguments that are not passed using a name=valuename=value syntax.
Function Argument-Matching Function Argument-Matching FormsForms Positional: Positional: matched left to right.def func(name)def func(name)func(value)func(value) Keywords:Keywords: matched by the argument name. def func(name)def func(name)func(name=value)func(name=value) Varargs:Varargs: catch unmatched arguments. def func(*name) def func(*name) # match remaining positional# match remaining positional # args(in a tuple)# args(in a tuple)def func(**name) def func(**name) # match remaining keyword# match remaining keyword
# args(in a dictionary)# args(in a dictionary) Defaults:Defaults: specify values for arguments that are not passeddef func(name=value)def func(name=value)
Keyword ExamplesKeyword Examples
>>> def f(a,b,c): print a,b,c>>>f(1,2,3) # by position
>>>f(c=3,b=2,a=1) # keyword args
>>>f(1,c=3,b=2) #mix positional and keyword args
Keyword and Default Keyword and Default ExamplesExamples KeywordsKeywords:
Self-documenting In conjunction with defaults
>>>def f(a,b=2,c=1):print a,b,c
>>>f(1)>>>f(a=1)
>>>f(2,4)>>>f(2,4,5)
>>>f(2,c=6)
Arbitrary Argument Arbitrary Argument ExamplesExamples Collect unmatched positional positional arguments into a tupletuple:>>>def f(*args): print args>>>def f(*args): print args
>>>f()>>>f(1)>>>f(1,2,3,4) Collect unmatched keywordkeyword arguments into a
dictionarydictionary:>>>def f(**args): print args>>>def f(**args): print args>>>f()>>>f(a=1,b=2)>>>f(b=1,c=2,a=3,d=4)
Flexible SignatureFlexible Signature
>>>def f(a,*pargs,**krags): print a,pargs,kargs
>>>f(1,2,3,x=1,y=‘234’)
Min ExampleMin Example Make a function that compute a minimum value from:
An arbitrary set of element (*args). Arbitrary set of object datatypes(polymorphism).
>>>def min1(*args): res=args[0] for arg in args[1:]: if arg<res: res=arg return arg >>>def min2(first,*rest): for arg in rest: if arg<first: first=arg return first>>>def min3(*args): tmp=list(args); tmp.sort(); return tmp[0]
Argument MatchingArgument Matching In a call, all keywordkeyword arguments must appear after all non-keywordafter all non-keyword arguments. In a function header, *name*name must appear after normal arguments and defaultsafter normal arguments and defaults, **name**name must appear lastlast.
Steps for assigning done by Python:1. Assign non-keyword arguments by position.2. Assign keyword args by matching names.3. Assign extra non-keyword args to *name tuple4. Assign extra keyword to **name dictionary.5. Assign default values to unassigned args in header.