Python Development [Part 5]: Basic Functions

Posted by monotoko on Fri, 17 May 2019 20:12:09 +0200

Function: Function definition keyword def followed by function name

def: Function name (parameter):

       
    ...
Function body
    ...
Return value

Case study:

  

# Defined function
def say_hei():
    print('hello world!!')

# function call
say_hei()

 

Calling function

Function call: function name with parentheses
 1 Find the name first
 2 Call code by name

The definition of function mainly includes the following points:

  • def: Keyword for function
  • Function name: The name of the function, which will be called later according to the name of the function.
  • Function body: A series of logical calculations are carried out in the function, such as sending mail, calculating the maximum number in [11, 22, 38, 888, 2], etc.
  • Parameters: Provide data for function bodies
  • Return value: When the function has been executed, it can return data to the caller.

Two, parameters

The function has three different parameters:

  • General parameter
  • # ######### Defined function ######### 
    
    # name is called the formal parameter of function func.
    def func(name):
        print('%s hello!'%name)
    
    # ######### Execution function ######### 
    #  'zhangsan'is called the actual parameter of the function func.
    func('zhangsan')
    

      

  • Default parameters
  • def func(name, age = 18):
        
        print("%s:%s" %(name,age))
    
    # Specified parameters
    func('zhangsan', 19)
    # Use default parameters
    func('lisi')
    
    Note: Default parameters need to be placed at the end of the parameter list
    

      

  • dynamic parameter
def func(*args):
    print (args)

# Mode 1 of Implementation
func(11,33,4,4454,5)

# Mode 2 of implementation
li = [11,2,2,3,3,4,54]
func(*li)

  

def func(**kwargs):

    print (args)


# Mode 1 of Implementation
func(name='zhangsan',age=18)

# Mode 2 of implementation
li = {'name':'zhangsan', age:18, 'gender':'male'}
func(**li)

  

def func(*args, **kwargs):

    print(args)
    print(kwargs)

  

Built-in function

 

Functional classification

# 1. Built-in functions
 To facilitate our development, for some simple functions, the python interpreter has defined functions for us, namely built-in functions. For built-in functions, we can use them without having to define them in advance, such as len(),sum(),max().
ps: In the end, we'll give you a detailed description of commonly used built-in functions.

# 2. Custom function
 It is obvious that built-in functions can provide limited functions, which requires us to customize our own functions to achieve some functions in advance according to our needs. Later, when encountering application scenarios, we can call custom functions. for example

Principles of Function Use: Define first, then call

 

Functions are "variables" and "variables" must be defined before being referenced. To refer directly to a function without a definition is to refer to a variable name that does not exist.
#Test one
def test():
    print('from test')
    func()
test() #Report errors

#Test two
def func():
    print('from func')
def test():
    print('from test')
    func()
test() #normal

#Test three
def test():
    print('from test')
    func()
    
def func():
    print('from func')
test() #Can you make a mistake?


#Conclusion: The use of functions must follow the following principles: first define, then call.
#When we use functions, we must clearly distinguish between the definition phase and the invocation phase.

#Definition phase
def test():
    print('from test')
    func()
def func():
    print('from func')
#Calling phase
test()

 

Nested calls to functions

  def testB():
        print('---- testB start----')
        print('Here is testB Code for function execution...(ellipsis)...')
        print('---- testB end----')


    def testA():

        print('---- testA start----')

        testB()

        print('---- testA end----')

    testA()

Results:

  ---- testA start----
    ---- testB start----
    Here is the code that the testB function executes... (omitted)...
    ---- testB end----
    ---- testA end----

  

Summary:

  • Another function is called in one function, which is called nested function call.

  • If another function B is called in function A, then all tasks in function B are executed before returning to the last function A.

Application

# Find the sum of three numbers
def sum3Number(a,b,c):
    return a+b+c # The return can be followed by either a numerical value or an expression.

# Complete the average of three numbers
def average3Number(a,b,c):

    # Because the sum3Number function has completed the sum of three numbers, it only needs to be called.
    # That is to say, the three received numbers can be passed as arguments.
    sumResult = sum3Number(a,b,c)
    aveResult = sumResult/3.0
    return aveResult

# Call the function to complete the average of three numbers
result = average3Number(11,2,55)
print("average is %d"%result)

  

local variable

 

  • A local variable is a variable defined within a function.
  • Different functions can define local variables with the same name, but each one has no effect.
  • The role of local variables, in order to temporarily save data, we need to define variables in the function to store, which is its role.

global variable

    # Define global variables
    a = 100

    def test1():
        print(a)

    def test2():
        print(a)

    # Calling function
    test1()
    test2()

  

The problem of identical names of global and local variables

 

Modify global variables keywords: Global

  • A variable defined outside a function is called a global variable.
  • Global variables can be accessed in all functions
  • If you modify a global variable in a function, you need to declare it using global, otherwise something goes wrong
  • If the name of the global variable is the same as that of the local variable, then the local variable is used.

 

Variable types of global variables

>>> a = 1
>>> def f():
...     a += 1
...     print a
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
>>>
>>>
>>> li = [1,]
>>> def f2():
...     li.append(1)
...     print li
...
>>> f2()
[1, 1]
>>> li
[1, 1]

  

  • The essence of not modifying global variables without using global to declare global variables in functions is not modifying the direction of global variables, that is, not pointing global variables to new data.
  • For global variables of immutable type, it is impossible to modify global variables without using global because the data it points to cannot be modified.
  • For variable types of global variables, global variables can be modified without using global because the data they point to can be modified.

Recursive function

If a function does not call other functions internally, but itself, it is a recursive function.

Look at the law of factorial

1! = 1
2! = 2 × 1 = 2 × 1!
3! = 3 × 2 × 1 = 3 × 2!
4! = 4 × 3 × 2 × 1 = 4 × 3!
...
n! = n × (n-1)!

  

principle

Anonymous function

Small anonymous functions can be created with lambda keywords. This function is named after omitting the standard steps of declaring a function with def.

The grammar of lambda functions contains only one statement, as follows:

 

 lambda [arg1 [,arg2,.....argn]]:expression

 

Example

    sum = lambda arg1, arg2: arg1 + arg2

    #Call the sum function
    print ("Value of total : ", sum( 10, 20 ))
    print ("Value of total : ", sum( 20, 20 ))

 

# Anonymous function keyword: lambda
l = lambda x: x + 1
print(l(5))
print("=================== map function==============")
jia = lambda x: x + 1;
jian = lambda x: x - 1
chen = lambda x: x * 1
chu = lambda x: x / 1


def map_text(func, array):
    arr1 = []
    for i in array:
        f = func(i)
        arr1.append(f)
    return arr1


arr = [1, 2, 3, 4, 5]
new_array = map_text(lambda x: x - 1, arr)
print(new_array)
print("=================== filter function==============")


def filter_text(func, array):
    new_array = []
    for i in array:
        if func(i):
            new_array.append(i)
    return new_array


str_array = ['zhangsan_sb', 'lisi_sb', 'wanger', 'mazi']
s = filter_text(lambda x: x.endswith('sb'), str_array)
print(s)
print("=================== reduce function==============")


def reduce_text(func, array, init=None):
    if init is None:
        sum = array.pop(0)
    else:
        sum = init
    for i in array:
        sum = func(sum, i)
    return sum


int_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
su = reduce_text(lambda x, y: x + y, int_array)
print(su)

  

Closure function

#Internal functions contain references to external scopes rather than global scopes

#Tip: We used to pass external values to functions through parameters. Closure provides another way of thinking. Wrap it up, wrap it up, wrap it up.

        def counter():
            n=0
            def incr():
                nonlocal n
                x=n
                n+=1
                return x
            return incr

        c=counter()
        print(c())
        print(c())
        print(c())
        print(c.__closure__[0].cell_contents) #View the elements of closures

Significance and Application of Closure

#The meaning of closure: The returned function object is not only a function object, but also encloses a scope, which makes the function use its outer wrapped scope preferentially wherever it is called.
#Application: Delayed Computing (originally we were referencing, now we are wrapping up)
    from urllib.request import urlopen

    def index(url):
        def get():
            return urlopen(url).read()
        return get

    baidu=index('http://www.baidu.com')
    print(baidu().decode('utf-8'))

Topics: Python Lambda