Python modular programming (higher order functions)

Keywords: Python Data Analysis data visualization

Recursive function

Recursive function is to define a function, and then call this function within the function
There must be an end in the recursive function, or it will be called one by one until more layers are called and the stack overflows
A recursive function is an entry layer by layer and a return layer by layer

Preliminary understanding of recursive function
# Preliminary understanding of recursive function 3 2 1 0
def digui(num):
    print(num) # 3 2 1 0
    # Detects whether the current value reaches zero
    if num > 0:
        # Calling the function itself
    print(num) # 0 1 2 3


Parse the execution process of the current recursive function:
digui(3) ==> 3 
    digui(3-1) ==> 2
        digui(2-1) ==> 1
            digui(1-1) ==> 0
            digui(0) ==> 0
        digui(1) ==> 1
    gidui(2) ==>2
digui(3) ==> 3

Callback function

The parameters in a function can be of any type. Can the parameters be a function?

If the parameter required to be passed in a function is a function as a parameter, and the passed function is used in the function, then this function can be called a callback function

# Define a function. One parameter in the function must be another function
# Function with callback function parameters
# def func(f):
    # print(f,type(f))
    # And the function of the row is called in the function.
    # f()

# Callback function
# def love():
#     print('123')
# func(love)

Closure function

Since the function can be passed as a line parameter and as a callback function, what if a function is returned in a function?

An inner function is returned in a function, and the returned inner function also uses the local variables in the outer function, which is the closure function


  1. A local variable is defined in the outer function and used in the inner function
  2. The inner function is returned in the outer function, and the returned inner function is the closure function
  3. ⚠ It mainly protects the local variables in the external function, which can be used without being destroyed
  4. To detect whether a function is a closure function, you can use the function name__ closure__ If it is a closure function, return cell
# Define a function
def person():
    money = 0  # A local variable is defined in the function
    # Inner function of work definition
    def work():
        nonlocal money   # The temporary variable of the outer function is used in the inner function
        money += 100
    # The inner function is returned in the outer function, which is the closure function
    return work

res = person() # return work  res = work
res() # res() == work()
# At this time, no operation can be performed on the local variable money in the global,
# Function of closure: it protects the variables in the function from external influence, but it can not affect the use

Anonymous function lambda expression

Anonymous function means that you can not use def definition, and does the function have a name

In python, you can use lambda expressions to define anonymous functions

Note: lambda expression is only an expression, not a code block, so lambda is also called a function of one line of code

lambda expressions also have row parameters and cannot access any data other than their own row parameters, including global variables

lambda [parameter list]:Return value

# Encapsulate a function for addition
# Ordinary function
def jia(x,y):
    return x+y

# print(jia(2,3))

# Change to lambda expression to encapsulate
res = lambda x,y:x+y
# print(res(4,4))

# lambda expression with branch structure
#  lambda parameter list: true interval if expression determines else false interval
res = lambda sex:"very man" if sex=='male' else "very nice"


Iterator is one of the most distinctive features in python and a way to access collection elements

An iterator is an object that remembers where to access the traversal

Access starts from the first element of the collection until all the elements in the collection are accessed

Iterators can only be convenient from front to back, not backward

An object that can be called by the next() function and continuously return the next value is called an Iterator (Iterator iterator object)


Function: turn the iteratable object into an iterator object
Parameters: iteratable objects (str, list, tuple, dict)
Return value: iterator object
Note: an iterator must be an iteratable object, but an iteratable object is not necessarily an iterator


The next() function can call the iterator and return the next data in the iterator

Value scheme of iterator

  1. The next() call fetches data once at a time until the data is fetched
  2. list() uses the list function to directly fetch all the data in the iterator
  3. Use the for loop to iterate over the iterator's data
The characteristics of iterator value. Take one less until all are taken, and an error will be reported if you get it again

Methods for detecting iterators and iteratable objects

from import Iterator,Iterable                   
varstr = '123456'                                               
res = iter(varstr)                                              
# The type() function returns the type of the current data,                                           
# isinstance() detects whether a data is a specified type                                 
r1 = isinstance(varstr,Iterable) # True iteratable object                   
r2 = isinstance(varstr,Iterator) # False is not an iterator                
r3 = isinstance(res,Iterable) # True iteratable object                      
r4 = isinstance(res,Iterator) # True is an iterator                     
# An iterator must be an iteratable object, and an iteratable object does not have to be an iterator                                           

Posted by aeonsky on Sat, 27 Nov 2021 22:31:34 -0800