2014年11月23日

Python Study (8) – Function


Introduction

Function is a Python’s basic structure. Function often is used to reuse code. you can repeat task that define a function for code reuse.

Function Advantage 

(1) Maximizing code reuse and minimizing redundancy
     In developing software,  don't repeat yourself is a a principle . We use function to achieve the goal in Python.A section code is adopted many times or offer other to use. We need to package to a function and offer many time for reuse .

(2) Procedural decomposition
A flow program is combined from



Function component 

(1) def

  • Syntax
def name(arg1, arg2….) :
    statements …
  • Example

def add(a, b):
           print(a+b)
>>>add(1,2)
3

(2) return

  • Syntax
def name(arg1, arg2….) :
    statements …
return result
  • Example

def add(a, b):
return a+b

>>>print(add(1,2))
3

(3) lambda
     lambda is keyword in python, It mainly is used to create anonymous function.

  • Syntax
lambda arg1, arg2, ....: statments # lambda is equal to follow as :
def fun(arg1, arg2,….) :   
return result
  • Example

>>> add = lambda a, b : a+b
>>> add
<function <lambda> at 0x0000000003327D08>

>>> add(1,2)
3

(3)lambda

Variable Scope 

>>> k=1
>>> def add(a,b):
    k=10
    print(k)

>>>k
1
>>>add(1,2)
10

Why k value is different in add function and outside add function ? 
1.Local variable : In a function , A variable is declared  and the variable only use in function
2. nested variable: In nested functions, A variable is declared in enclosing function.
3. global variable : A variable is declared  and the variable is hold  in file
4. nonlocal variable: In Python3.x  it introduce a new nonlocal statment , It only define in a function.

Example

>>> counter = 1
>>> def increament():
         global counter
         counter = 10
         counter = counter +1
         print(counter)

>>> increament()
11
>>> counter
11

 



 








Build-in Scope :
    Servial variable is builed-in python’s library.

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed',
'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum',
'super', 'tuple', 'type', 'vars', 'zip']


 















 

沒有留言:

張貼留言