Function Basics
Function
In this chapter, we will move on to explore a set of additional statements that create functions of our own
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.
Why Function?
Functions serve two primary development roles:
Code Reuse: Functions allows us to group and generalize code to be used arbitrarily many times after it is defined
Procedure decomposition: Functions also provide a tool for splitting systems into pieces---one function for each subtask
“def” statement The def statement creates a function object and
assigns it to a name. the def general format:
def <name> ( ):<statements>
the statement block becomes the function’s body---the code Python executes each time the function is called
Function Example
def star(): num=int(raw_input("please input a number")) for i in range(num+1): print '*' * i
star() # we call “star” function once
Function Exampledef star(): num=int(raw_input("please input a number")) for i in range(num+1): print '*' * i
for i in range(3):star() # we call “star” function 3 times here
“def” statement Now we try to see the def format with arguments:
def <name>(arg1, arg2, …, argN):
<statement>
Function Example with one Argument
def star(num):
for i in range(num+1):
print '*' * i
for i in range(3):
num = num=int(raw_input("please input a number"))
star(num) # we call “star” function 3 times here
Function Example with 2 arguments
def multiply(x,y):value=x*yprint value
multiply(4,10)multiply(3,6)multiply(2,18)
Function Example with 3 arguments
def multiply(x,y,z):value=x*y*zprint value
multiply(4,10,1) #generate result 40multiply(4,10) #error message: multiply()
takes exactly 3 arguments (2 given)
“def” statement Now we try to see the def format with arguments
and return function:
def <name>(arg1, arg2, …, argN):
…
return <value>
Function Example
def times(x,y):value=x*yreturn value
aa = times(2,4) #aa=8aa = times(3.14,4)#aa=12.56aa = times(“ha”,4)#aa=“hahahaha”list=[1,2,3,4]aa = times(list,2) #aa=[1,2,3,4,1,2,3,4]
Function Example
def times(x,y):
for i in range(len(x)):
x[i]=x[i]*y
aa=[1,2,3,4]
times(aa, 2)
Scope 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 Basics 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 Statement Global names must be declared only if the assigned 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
Passing 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
Simulate Output Parameters
returnreturn sends back any sort of object It could return multiple valus, 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
Arguments Matching Modes
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.
Arguments Matching Modes
Positional: Positional: matched left to rightdef func(name)def func(name)func(value)func(value) Keywords:Keywords: matched by the argument namedef 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 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 Examples
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 Arguments Examples
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 Signature
>>>def f(a,*pargs,**krags): print a,pargs,krags
>>>f(1,2,3,x=1,y=‘234’)