240 likes | 330 Views
Function Basics. Function. In this chapter, we will move on to explore a set of additional statements that create functions of our own
E N D
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 (subroutine, procedure) is a package of code (a set of statements) that can be called repeatedly with different inputs (parameters) and outputs 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 Example def 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*y print value multiply(4,10) multiply(3,6) multiply(2,18)
Function Example with 3 arguments def multiply(x,y,z): value=x*y*z print value multiply(4,10,1) #generate result 40 multiply(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*y return value aa = times(2,4) #aa=8 aa = times(3.14,4)#aa=12.56 aa = 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 • Namespace is the place where names live • The location of name’s assignment defines the scope of the name visibility • Names defined inside a def can be seen only by the code inside the def • Names defined inside a def not clash with variables outside the def, 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: 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> >>>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”). • Changing a mutable object argument in a function may impact a caller (“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 • return 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: matched left to right. • 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=value syntax. • Varargs: catch unmatched positional or keyword arguments. Function can use special arguments preceded with a * characters to collect arbitrarily extra arguments. • Defaults: specify values for arguments that are not passed using a name=value syntax.
Arguments Matching Modes • Positional: matched left to right def func(name) func(value) • Keywords: matched by the argument name def func(name) func(name=value) • Varargs: catch unmatched arguments. def func(*name) # match remaining positional # args(in a tuple) def func(**name) # match remaining keyword # args(in a dictionary) • Defaults: specify values for arguments that are not passed 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 • Keywords: • 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 arguments into a tuple: >>>def f(*args): print args >>>f() >>>f(1) >>>f(1,2,3,4) • Collect unmatched keyword arguments into a dictionary: >>>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’)