function basics

24
Function Basics

Upload: hasana

Post on 12-Jan-2016

32 views

Category:

Documents


0 download

DESCRIPTION

Function Basics. Function. In this chapter, we will move on to explore a set of additional statements that create functions of our own - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Function Basics

Function Basics

Page 2: 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.

Page 3: Function Basics

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

Page 4: Function Basics

“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

Page 5: Function Basics

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

Page 6: Function Basics

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

Page 7: Function Basics

“def” statement Now we try to see the def format with arguments:

def <name>(arg1, arg2, …, argN):

<statement>

Page 8: Function Basics

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

Page 9: Function Basics

Function Example with 2 arguments

def multiply(x,y):value=x*yprint value

multiply(4,10)multiply(3,6)multiply(2,18)

Page 10: Function Basics

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)

Page 11: Function Basics

“def” statement Now we try to see the def format with arguments

and return function:

def <name>(arg1, arg2, …, argN):

return <value>

Page 12: Function Basics

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]

Page 13: Function Basics

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)

Page 14: Function Basics

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

Page 15: Function Basics

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.

Page 16: Function Basics

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

Page 17: Function Basics

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

Page 18: Function Basics

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

Page 19: Function Basics

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.

Page 20: Function Basics

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)

Page 21: Function Basics

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

Page 22: Function Basics

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)

Page 23: Function Basics

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)

Page 24: Function Basics

Flexible Signature

>>>def f(a,*pargs,**krags): print a,pargs,krags

>>>f(1,2,3,x=1,y=‘234’)