Chapter 9: Functions in Python

1. Function creation and calling

1.1 What is a function

  • A function is a piece of code that performs a specific task and a specific function

1.2 Why do we need functions

  • reuse code
  • hide implementation details
  • Improve program maintainability
  • Improve program readability and facilitate debugging

1.3 Creation of functions

def 函数名([输入参数])
	函数体
	[return xxx]

1.4 Function call

函数名([实际参数])

code demo

def calc(a, b):
    c = a + b
    return c


result = calc(10, 20)
print(result)

Second, the parameter passing of the function

The position of the formal parameter is at the definition of the function

The position of the actual parameter is at the call site of the function

Formal and actual parameter names can be different

2.1 Positional arguments

  • Parameter passing according to the position corresponding to the formal parameter
  • icon

image-20230506200826294

2.2 Keyword arguments

  • Actual parameter passing by formal parameter name
  • icon

image-20230506201009121

code demo

def calc(a, b):  # a,b 为形参,形参的位置是在函数的定义处
    c = a + b
    return c


result = calc(10, 20)  # 10,20 为实参,实参的位置在函数的调用处
print(result)

result2 = calc(b=10, a=20)  # 关键字参数,=左侧的变量名称为关键字参数
print(result2)

2.3 Memory Analysis Diagram of Parameter Passing

在函数调用过程中,进行参数的传递
如果是不可变对象,在函数体的修改不会影响实参的值    如:arg1的修改为100,不会影响n1的值
如果是可变对象,在函数体内的修改会影响实参的值     如:arg2的修改 append(10),会影响到n2的值

image-20230506201325782

code demo

def fun(arg1, arg2):
    print('arg1:', arg1)
    print('arg2:', arg2)
    arg1 = 100
    arg2.append(10)
    print('arg1:', arg1)
    print('arg2:', arg2)


n1 = 11
n2 = [22, 33, 44]
print('函数输入前:-----------')
print('n1:', n1)
print('n2:', n2)

fun(n1, n2)  # 位置传参,arg1,arg2为函数定义处的形参,n1,n2为函数调用处的实参
print('函数输入后:-----------')
print('n1:', n1)
print('n2:', n2)

3. The return value of the function

When a function is defined, whether it needs to return a value depends on the situation

  • function return value
    • If the function has no return value [after the function is executed, there is no need to provide data to the calling site] return can be omitted
    • If there is only one return value of the function, the direct return type
    • If there are multiple return values ​​of the function, the returned result is the ancestor

Fourth, the function parameter definition

4.1 Function definition default value parameter

  • When the function is defined, set the default value for the formal parameter, and only need to pass the actual parameter when it does not match the default value

code demo

def fun(a, b=10):  # b为默认值参数
    print(a, b)


# 函数的调用
fun(100)  # a=100,b=10,    b采用默认值
fun(20, 30)  # a=20,b=30    b默认值不符的时候才需要传递实参

4.2 Variable number of positional arguments

  • When defining a function, it may not be possible to determine the number of passed positional parameters in advance, you can use variable positional parameters
  • Only one variable number of positional parameters can be defined
  • Using *variable-number positional parameters
  • The result is a tuple

code demo

def fun(*args):  # 函数定义时,可变的位置参数
    print(args)


# 传递1个参数
fun(10)
# 传递2个参数
fun(20, 20)
# 传递3个参数
fun(20, 20, 20)

4.3 Variable Number of Keyword Arguments

  • When defining a function, it may not be possible to determine the number of keyword parameters passed in advance, and variable keyword parameters can be used
  • Only one variable number of keyword arguments can be defined
  • Using **keyword parameters with a variable number of definitions
  • The result is a dictionary
  • During the definition of a function, there are both variable number of keyword parameters and variable number of positional parameters; the requirement is 个数可变的关键字形参placed 个数可变的位置形参before. Right nowdef fun3(*args, **kwargs):

code demo

def fun1(**args):
    print(args)


# 传递1个参数
fun1(a=10)
# 传递3个参数
fun1(a=20, b=3, c=40)

4.4 Summary

serial number the type of the parameter function definition function call Remark
1 positional argument
converts each element in the sequence to a positional argument use *
2 keyword arguments
Convert each key-value pair in the dictionary into a keyword argument use**
3 default value parameter
4 keyword parameter use *
5 variable number of positional parameters use *
6 variable number of keyword parameters use**

code demo

def fun(a, b, c):  # a,b,c在函数的定义处,所以是形参
    print('a=', a)
    print('b=', b)
    print('c=', c)


# 函数的调用
fun(10, 20, 30)  # 函数调用时的参数传递,成为位置传参,实参
lst = [11, 22, 33]
# fun(lst)  # 报错
fun(*lst)  # 在函数调用时,将列表中的每个元素都转换成位置实参传入

fun(a=100, b=200, c=300)  # 函数的调用,关键字实参
dic = {
    
    'a': 111, 'b': 222, 'c': 333}
fun(**dic)  # 在函数调用时,将子弹中的键值对都转换成位置实参传入

Five, the scope of the function

scope

  • Program code can access the area of ​​the variable
  • According to the effective range of variables can be divided into
    • local variable
      • Variables defined and used within a function are only valid within the function
      • Local variables use globaldeclarations, and this declaration becomes a global variable
    • global variable
      • Variables defined outside the function can be used inside and outside the function

code demo

def fun(a, b):
    c = a + b  # c,就称为局部变量,因为c在是函数体内进行定义的变量,a,b为函数的形参,作用范围也是函数内部,相当于局部变量
    print(c)


# print(c)  ,因为a,c超出了起作用的范围(超出了作用域)
# print(a)

name = 'eden'  # name的作用范围为函数内部和外部都可以使用 -->称为全局变量
print(name)


def fun2():
    print(name)


# 调用函数
fun2()


def fun3():
    global age  # 函数内部定义的变量,局部变量,局部变量使用global声明,这个变量实际上就变成了全局变量
    age = 20
    print(age)


fun3()
print(age)

Six, recursive function

  • What is a recursive function
    • A function becomes recursive if the function itself is called within the body of the function
  • components of recursion
    • Recursive calls and recursive termination conditions
  • recursive call procedure
    • Every time a function is called recursively, a stack frame will be allocated in the stack memory
    • Every time the function is executed, the corresponding space will be released
  • Advantages and disadvantages of recursion
    • Advantages: take up a lot of memory, low efficiency
    • Disadvantages: simple ideas and code

6.1 Computing factorials using recursion

icon

image-20230510140432909

code demo

def fac(n):  # n为要计算阶乘的数
    if n == 1:
        return 1
    else:
        return n * fac(n - 1)


print(fac(6))

6.2 Fibonacci sequence

1	1	2	3	5	8	13
第1、2项的数为1
第n项的数为(n-1)的值+(n-2)的值

def fib(n):
    if n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        return fib(n - 1) + fib(n - 2)


# 裴波那契数列的第6位上的数
print(fib(6))

# 输出数列的前6为上的数
for i in range(1, 7):
    print(fib(i))

# 输出数列的前6为上的数,并存放在一个列表值
list = []
for i in range(1, 7):
    list.append(fib(i))
print(list)

Guess you like

Origin blog.csdn.net/polaris3012/article/details/130599929