Python (9)-the use of functions in Python entry


Preface

1. How to create (define) a function

def 函数名(参数列表):
    //实现特定功能的多行代码
    return [返回值]
  • The input of a function is called a parameter, and the output of a function is called a return value.
  • The function code block starts with the def keyword, followed by the function identifier name and parentheses (). Any incoming parameters and arguments must be placed in the middle of the parentheses. The parentheses can be used to define parameters.
  • When creating a function, even if the function does not require parameters, a pair of empty "()" must be reserved
  • If you want to define an empty function without any function, you can use the pass statement as a placeholder.
  • return [expression] End the function, optionally returning a value to the caller. Return without expression is equivalent to returning None. In the function, the code after return will not be executed. Once the return is executed, the function will end automatically

Create a function to determine the size of two numbers

def max(a,b):                  ##  函数名(参数列表), a,b为形参
    return a if a>=b else b    ##选择性地返回一个值给调用方

2. Function call

The basic syntax format of function call:

  • [Return value] = Function name ([Formal parameter value]) The
    function name refers to the name of the function to be called; the formal parameter value refers to the value of each formal parameter that is required to be passed in when the function is created. If the function has a return value, we can receive the value through a variable, or not.
resault=max(2,5)  ##resault变量接受返回值
print(resault)    ##打印resault

3. Types of parameters

参数的类型
       - 形参: 形式参数,不是真实的值(定义函数时的参数)
       - 实参:实际参数, 是真实的值(调用函数时的参数)
def max(a,b):           ## a,b为形参
    return a if a>=b else b
resault=max(2,5)        ## 2,5为实参
print(resault)

4. The comment of the function

Function comments include:

  • Parameter comment: marked with a colon (:)
  • Return value comment: marked with ->
  • Function comment in the function body """ fill in the function description """ comment and fill in the corresponding function
def max(a:int,b:int)->int: 
    """
    :param a: 整形a
    :param b: 整形b
    :return: 返回值为a和b中的最大值
    """
    if isinstance(a,int)and isinstance(b,int):
        return a if a>=b else b
    else:
        return 0
resault=max(2,5)
print(resault)
print(help(max)) ## 查看自定义函数的帮助
输出:
5
Help on function max in module __main__:

max(a: int, b: int) -> int
    :param a: 整形a
    :param b: 整形b
    :return: 返回值为a和b中的最大值

None

5. Namespace and scope

5.1 Namespace

Built-in space: that is, the function that comes with the python interpreter is similar to print input len.
Global space: the space that the current py file needs to open is stored in the global space.
Local space: the space opened up in the function is the local space.
Loading order: built-in space-global space-local Space
Value order: local space-global space-built-in space

5.2 Scope of variables

5.2.1 Global scope

  • The global scope is created when the program is executed, and destroyed at the end of the program execution
  • All areas other than functions are global scope
  • Variables defined in the global scope belong to global variables, and global variables can be accessed anywhere in the program

5.2.2 Function scope

  • The function scope is created when the function is called and destroyed at the end of the call
  • Each time the function is called, a new function scope is generated
  • Variables defined in the scope of the function are all local variables, which can only be accessed inside the function

5.2.3 Global and local variables

  • The scope of the global variable is the entire program, and the scope of the local variable is the subroutine that defines the variable.
  • When the global variable and the local variable have the same name: in the subroutine where the local variable is defined, the local variable works; the global variable works in other places.

(1) Global variables: variables that take effect globally, variables outside the function.

a=3  ##a为全局变量
def prt():
    return a
print(prt())
输出:3

(2) Local variables: locally effective variables, variables inside functions.

a=3               ## 此处的a为全局变量
def prt():
    a=2           ## 此处的a为局部变量
    return a
print(prt())      ## 2
print(a)          ## 3

5.2.4 Modify global variables inside a function

  • If you want to modify the global variables in the function, you cannot modify it directly. You need to use the global keyword to declare that the modified variable is a global variable.
  • Immutable data types must be declared globally to modify global variables, and variable data types are not required.
    • Variable data types: list (list), dict (dictionary), sets (collection)
    • Immutable data types: numeric, str, tuple
a=3           ##不可变数据类型
user=[]       ##可变数据类型
def prt():
    global a   ## 声明a为全局变量
    a=2
    user.append('user1')
    print(a,user)
prt()         ## 2 ['user1']
print(a)      ## 2

6. Four common types of formal parameters in python

6.1 Required parameters

Parameters that must be passed

def max(a,b):        ## 定义函数时指定形参
    return a if a>=b else b
resault=max(1,3)     ##  调用函数时,来传递实参
print(resault)

6.2 Default parameters

Parameters that can be passed or not passed. In the function below, b is the default parameter. If you do not specify the value of b when calling the max function, the value of b is the default value 2 at this time; if you specify the value of b when calling the function, then specify The value of b will override the default value of b

def max(a,b=2):       ## 定义形参时,可以为形参指定默认值
    return a if a>=b else b
resault=max(1)
print(resault)
输出: 2
 def max(a,b=2):
    return a if a>=b else b
resault=max(1,5)
print(resault)
输出:5

6.3 Variable parameters

  • The number of parameters will change, you can pass 0, 1, 2, 3,...n
  • args is a tuple
def max(*args):
    return args
resault=max(1,5,6,7)
print(resault)
输出:
(1, 5, 6, 7)
  • There can only be one parameter with an asterisk
  • The parameters with an asterisk can be used in conjunction with other parameters
  • All parameters are saved to the tuple of args
  • Variable parameters do not have to be written at the end, but note that all parameters after the parameter with * must be passed in the form of keyword parameters
  • *Formal parameters can only receive positional parameters, but not keyword parameters

6.4 Keyword parameters

  • The number of parameters will change, you can pass 0, 1, 2, 3, ... n: key and value can be passed
  • kwargs are stored in the dictionary
def max(**kwargs):
    return kwargs
resault=max(a=1,b=2,c=5)
print(resault)
输出:
{
    
    'a': 1, 'b': 2, 'c': 5}

  • **Formal parameters can receive other keyword parameters, it will uniformly save these parameters into a dictionary
  • The key of the dictionary is the name of the parameter, and the value of the dictionary is the value of the parameter
  • **There can be only one formal parameter, and it must be written at the end of all parameters

7. Anonymous function

Anonymous function refers to a class of functions or subroutines that do not need to define an identifier. Python uses lambda syntax to define anonymous functions

  • Use an anonymous function to find the sum of two numbers
result=lambda a,b:a if a>=b else b
print(result(2,3))

Exercise 1

Insert picture description here

num=[0,7,0,2]
num.sort(key=lambda num: 0 if num==0 else 1,reverse=True)
print(num)
输出:
[7, 2, 0, 0]

Exercise 2

Before the even row, after the odd row

num1=[3,7,0,2]
num1.sort(key=lambda num: 1 if num%2==1 else 0)
print(num1)

8. Recursive function

  • The law of recursion
  • Conditions for exiting recursion

Exercise 1: Find the factorial of 10

  • analysis:
    • The law of recursion: 10! =10 9!, 9! =9 8! …1!=1
    • Conditions for exiting recursion: 1!=1
def factorial(n):
    if n==1:
        return 1 ## n=1时退出递归,返回值为1
    else:
        return n*factorial(n-1)
print(factorial(10))

Exercise 2: Fibonacci sequence (Fibonacci sequence), also known as the golden section sequence, refers to such a sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,...

  • The law of recursion:F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)
  • Conditions for exiting recursion:F(0)=0,F(1)=1
def fib(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fib(n-1)+fib(n-2)
print(fib(5))

This article ends here

Guess you like

Origin blog.csdn.net/weixin_41191813/article/details/113726582