Alibaba Cloud Python Training Camp (day7)


Introduction

Python treats functions as objects, and can be returned from another function to construct higher-order functions. For example, the parameters are functions and the return values ​​are functions.


One, function

1. Function definition and call

Function definition:

  • The function starts with the def keyword, followed by the function name and parentheses ().

  • The code executed by the function starts with a colon and is indented.

  • return [expression] End the function, optionally returning a value to the caller. Return without expression is equivalent to returning None.

     def functionname (parameters):
         "函数_文档字符串"
         function_suite
         return [expression]
    

Function call: The
demo code is as follows:

def printme(str):
    print(str)

printme("我要调用用户自定义函数!")  # 我要调用用户自定义函数!
printme("再次调用同一函数")  # 再次调用同一函数
temp = printme('hello') # hello
print(temp)  # None

3. Function documentation

The demo code is as follows:

def MyFirstFunction(name):
    "函数定义过程中name是形参"
    # 因为Ta只是一个形式,表示占据一个参数位置
    print('传递进来的{0}叫做实参,因为Ta是具体的参数值!'.format(name))
    
MyFirstFunction('老马的程序人生')  
# 传递进来的老马的程序人生叫做实参,因为Ta是具体的参数值!

4. Function parameters

Python functions have very flexible and diverse parameter forms, which can realize simple calls and pass in very complex parameters. The parameter forms from simple to complex are as follows:

  • Positional argument
  • Default argument
  • Variable argument
  • Keyword argument
  • Name keyword argument
  • Parameter combination

(1). Position parameters

def functionname(arg1):
       "函数_文档字符串"
       function_suite
       return [expression]

arg1-positional parameters, these parameters must be fixed in position when calling a function (call function).

(2). Default parameters

def functionname(arg1, arg2=v):
       "函数_文档字符串"
       function_suite
       return [expression]

arg2 = v-Default parameter = default value. When calling the function, if the value of the default parameter is not passed in, it is considered as the default value.
The default parameter must be placed after the positional parameter, otherwise the program will report an error.

The demo code is as follows:

def printinfo(name, age=19):
    print('Name:{0},Age:{1}'.format(name, age))

printinfo('zmt')  # Name:zmt,Age:8
printinfo('zmt', 20)  # Name:zmt,Age:20

(3). Variable parameters

As the name implies, a variable parameter means that the number of parameters passed in is variable, which can be 0, 1, 2 to any number, and is a parameter of variable length.

def functionname(arg1, arg2=v, *args):
      "函数_文档字符串"
       function_suite
       return [expression]
  • args-Variable parameters, which can be from zero to any number, automatically assembled into tuples.
  • Variable names with an asterisk (*) will store all unnamed variable parameters.

The demo code is as follows:

def printinfo(arg1, *args):
    print(arg1)
    for var in args:
        print(var)

printinfo(10)  # 10
printinfo(70, 60, 50)
#70 60 50

(4). Keyword parameters

def functionname(arg1, arg2=v, args, *kw):
       "函数_文档字符串"
       function_suite
       return [expression]

kw-keyword parameters, which can be from zero to any number, automatically assembled into a dictionary.

The demo code is as follows:

def printinfo(arg1, *args, **kwargs):
    print(arg1)
    print(args)
    print(kwargs)

printinfo(70, 60, 50)
# 70
# (60, 50)
# {}

printinfo(70, 60, 50, a=1, b=2)
# 70
# (60, 50)
# {'a': 1, 'b': 2}

The similarities and differences between variable parameters and keyword parameters are summarized as follows:

  • Variable parameters allow zero to any number of parameters to be passed in, and they are automatically assembled into a tuple when the function is called.
  • Keyword parameters allow zero to any number of parameters to be passed in, and they are automatically assembled into a dictionary (dict) inside the function. 5. Named keyword parameters

(5). Named keyword parameters

def functionname(arg1, arg2=v, args, *, nkw, *kw):
       "函数_文档字符串"
       function_suite
       return [expression]
  • *, nkw-named keyword parameter, the keyword parameter that the user wants to enter, the definition method is to add a separator * in front of nkw.
  • If you want to limit the names of keyword parameters, you can use "named keyword parameters"
  • When using named keyword parameters, pay special attention to the lack of parameter names.

The demo code is as follows:

def printinfo(arg1, *, nkw, **kwargs):
    print(arg1)
    print(nkw)
    print(kwargs)

printinfo(70, nkw=10, a=1, b=2)
# 70
# 10
# {'a': 1, 'b': 2}

printinfo(70, 10, a=1, b=2)
# TypeError: printinfo() takes 1 positional argument but 2 were given

(6). Combination parameters

To define a function in Python, you can use positional parameters, default parameters, variable parameters, named keyword parameters and keyword parameters. 4 of these 5 parameters can be used together, but note that the order of parameter definition must be:

  • Positional parameters, default parameters, variable parameters and keyword parameters.
  • Positional parameters, default parameters, named keyword parameters, and keyword parameters.

Pay attention to the syntax for defining variable parameters and keyword parameters:

  • *args is a variable parameter, args receives a tuple
  • **kw is a keyword parameter, kw receives a dict

Naming keyword parameters is to limit the parameter names that the caller can pass in, and to provide default values. Don't forget to write the delimiter * when defining named keyword parameters, otherwise positional parameters are defined.

Warning: Although you can combine up to 5 parameters, do not use too many combinations at the same time, otherwise the function is difficult to understand.

5. The return value of the function

Python's function return value is similar to the previously learned c and java

def 函数名(参数1,参数2)
     return 参数1+参数2

6. The scope of variables

  • In Python, the variables of the program are not accessible at all locations, and the access permissions depend on where the variable is assigned.
  • The variable defined inside the function has a local scope, which is called a local variable.
  • Variables defined outside the function have a global scope, which is called a global variable.
  • Local variables can only be accessed within the function in which they are declared, while global variables can be accessed within the scope of the entire program.

The demo code is as follows:

def discounts(price, rate):
    final_price = price * rate
    return final_price

old_price = float(input('请输入原价:'))  # 98
rate = float(input('请输入折扣率:'))  # 0.9
new_price = discounts(old_price, rate)
print('打折后价格是:%.2f' % new_price)  # 88.20

When the inner scope wants to modify the variables of the outer scope, the global and nonlocal keywords must be used.

The demo code is as follows:

num = 1

def fun1():
    global num  # 需要使用 global 关键字声明
    print(num)  # 1
    num = 123
    print(num)  # 123

fun1()
print(num)  # 123

Embedded functions and closures: The
demo code is as follows:

def outer():
    print('outer函数在这被调用')

    def inner():
        print('inner函数在这被调用')
        
    inner()  # 该函数只能在outer函数内部被调用
    
outer()    
# outer函数在这被调用
# inner函数在这被调用

#闭包是函数式编程的一个重要的语法结构,是一种特殊的内嵌函数。如果在一个内部函数里对外层非全局作用域的变量进行引用,那么内部函数就被认为是闭包。通过闭包可以访问外层非全局作用域的变量,这个作用域称为 闭包作用域。

def funX(x):
    def funY(y):
        return x * y
        
    return funY

i = funX(8)
print(type(i))  # <class 'function'>
print(i(5))  # 40


#如果要修改闭包作用域中的变量则需要 nonlocal 关键字
def outer():
    num = 10
    def inner():
        nonlocal num  # nonlocal关键字声明
        num = 100
        print(num)
        
    inner()
    print(num)
outer()
# 100
# 100

Recursive function: The
demo code is as follows:

#n! = 1 x 2 x 3 x ... x n

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)
    
print(factorial(5)) # 120


#斐波那契数列 f(n)=f(n-1)+f(n-2), f(0)=0 f(1)=1

def recur_fibo(n):
    if n <= 1:
        return n
    return recur_fibo(n - 1) + recur_fibo(n - 2)

lst = list()
for k in range(11):
    lst.append(recur_fibo(k))
print(lst)  
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

Two, Lambda-expression

1. The definition of anonymous functions

There are two types of functions in Python:

  • The first category: normal functions defined with the def keyword
  • The second category: anonymous functions defined with lambda keywords

Python uses the lambda keyword to create anonymous functions instead of the def keyword. It has no function name and its grammatical structure is as follows:

 lambda argument_list: expression
  • lambda-keywords to define anonymous functions.
  • argument_list-function parameters, they can be positional parameters, default parameters, keyword parameters, and the same type of parameters in the normal function.
  • :- Colon, add a colon between function parameters and expressions.
  • expression-just an expression, input function parameters, output some values.

note:

  • There is no return statement in expression, because lambda does not need it to return, and the result of the expression itself is the return value.
  • An anonymous function has its own namespace and cannot access parameters outside of its parameter list or in the global namespace.

The demo code is as follows:

def sqr(x):
    return x ** 2
print(sqr)
# <function sqr at 0x000000BABD3A4400>

y = [sqr(x) for x in range(10)]
print(y)
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

sumary = lambda arg1, arg2: arg1 + arg2
print(sumary(10, 20))  # 30

func = lambda *args: sum(args)
print(func(1, 2, 3, 4, 5))  # 15

2. Application of anonymous functions

Functional programming means that every piece of code is immutable and consists of pure functions. The pure function here means that the functions are independent of each other and do not affect each other. For the same input, there will always be the same output without any side effects.

  • Non-functional programming:

The demo code is as follows:

def f(x):
    for i in range(0, len(x)):
        x[i] += 10
    return x

x = [1, 2, 3]
f(x)
print(x)
# [11, 12, 13]
  • Functional programming:

The demo code is as follows:

def f(x):
    y = []
    for item in x:
        y.append(item + 10)
    return y

x = [1, 2, 3]
f(x)
print(x)
# [11, 12, 13]

Anonymous functions are often used in high-order functions in functional programming. There are two main forms:

  • Parameters are functions (filter, map)
  • The return value is a function (closure)

Application of filter and map functions:

  • filter(function, iterable) Filter the sequence, filter out the elements that do not meet the conditions, and return an iterator object. If you want to convert to a list, you can use list() to convert.
  • map(function, *iterables) maps the specified sequence according to the provided function

The demo code is as follows:

odd = lambda x: x % 2 == 1
templist = filter(odd, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(templist))  # [1, 3, 5, 7, 9]


m1 = map(lambda x: x ** 2, [1, 2, 3, 4, 5])
print(list(m1))  
# [1, 4, 9, 16, 25]

Guess you like

Origin blog.csdn.net/qq_44250569/article/details/108897010