• day03.1-函数编程


    python中函数的定义:

     1 def test (x,y):
     2     "The function definitions"
     3     z = x**y
     4     return z
     5 
     6 """
     7 def:定义函数的关键字
     8 test:函数名
     9 ():内可定义形参
    10 z=x**y:函数功能实现代码块
    11 return:运算结果返回
    12 """

    一. 函数的特征

        1. 当python中函数通过return语句返回多个值时,默认以元组方式打包后一次性返回。

         2. 位置参数调用方式:实参与形参位置一一对应;如test(2,3);

            关键字参数调用方式:实参与形参位置不必一一对应,但需指定形参名与对应的实参值;如test(y=3,x=2);

            当两种调用方式混合使用时,位置参数调用必须位于关键字参数调用后面;如test(2,y=3)。

         3. 默认参数:在函数定义时可以为其中某一参数赋予默认值;当调用该函数时,可以为默认参数传入实参,也可以使用默认值。如def test(x,type="mysql")。

         4. 参数组:* 列表,** 字典。

     1 def test (x,*args):
     2     print(x)
     3     print(args)
     4     print(args[0])
     5 
     6 test(1,2,3,4,5,6)
     7 print("--"*20)
     8 test(1,[2,3,4,5,6])
     9 print("--"*20)
    10 test(1,*[2,3,4,5,6])
    11 
    12 """
    13 运行结果:
    14     1
    15     (2, 3, 4, 5, 6)
    16     2
    17     ----------------------------------------
    18     1
    19     ([2, 3, 4, 5, 6],)
    20     [2, 3, 4, 5, 6]
    21     ----------------------------------------
    22     1
    23     (2, 3, 4, 5, 6)
    24     2
    25 """
     1 def test (x,**kwargs):
     2     print(x)
     3     print(kwargs)
     4 
     5 test(1,y=2,z=3)
     6 print("--"*20)
     7 test(1,**{"y":2,"z":3})
     8 
     9 """
    10 运行结果:
    11     1
    12     {'y': 2, 'z': 3}
    13     ----------------------------------------
    14     1
    15     {'y': 2, 'z': 3}
    16 """
     1 def test (x,*args,**kwargs):
     2     print(x)
     3     print(args)
     4     print(kwargs)
     5 
     6 test(11,22,33,44,y=55,z=66)
     7 print("--"*20)
     8 test(11,*[22,33,44],**{"y":55,"z":66})
     9 
    10 """
    11 运行结果:
    12     11
    13     (22, 33, 44)
    14     {'y': 55, 'z': 66}
    15     ----------------------------------------
    16     11
    17     (22, 33, 44)
    18     {'y': 55, 'z': 66}
    19 """
     1 def test1(name,age,gender):
     2     print(name)
     3     print(age)
     4     print(gender)
     5 def test2(*args, **kwargs):
     6     test1(*args, **kwargs)    #args=("alex",18,"male")  kwargs={}
     7 test2("alex",18,"male")
     8 
     9 """
    10 运行结果:
    11     alex
    12     18
    13     male
    14 """     

         5. 局部变量与全局变量

            在子函数中定义的变量称为局部变量,局部变量只在子函数运行期间有效;在主函数中定义的变量称为全局变量,全局变量在整个程序运行期间都有效;

            在子函数中声明、调用与修改全局变量,global 全局变量名;在子函数中声明、调用与修改上一级函数中变量,nonlocal 变量名;

     1 daxia = "令狐冲"
     2 print(daxia)    #在主函数中,访问全局变量daxia对应的值
     3 def test1():
     4     global daxia
     5     daxia = "风清扬"   #在子函数中,修改并访问全局变量值
     6 test1()
     7 print(daxia)       #检查test1修改后全局变量值
     8 
     9 """
    10 运行结果:
    11     令狐冲
    12     风清扬
    13 """
     1 def test1():
     2     daxia = "令狐冲"
     3     print(daxia)       #在子函数内部,访问局部变量daxia对应的值
     4     def test2():
     5         nonlocal daxia
     6         daxia = "风清扬"   #在子函数中,修改并访问上一级函数变量值
     7     test2()
     8     print(daxia)       #检查test2修改后局部变量值
     9 test1()
    10 
    11 """
    12 运行结果:
    13     令狐冲
    14     风清扬
    15 """ 

            当局部变量与全局变量同名时,在子函数运行期间,局部变量有效,在子函数退出后,全局变量有效。

     1 daxia = "令狐冲"
     2 def test1 ():
     3     daxia = "李寻欢"
     4     print(daxia)      #在子函数内部,访问局部变量daxia对应的值
     5 test1()
     6 print(daxia)    #在主函数中,访问全局变量daxia对应的值
     7 
     8 """
     9 运行结果:
    10     李寻欢
    11     令狐冲
    12 """

         6. 函数作用域由函数定义过程决定,与函数的调用过程无关。

    二. 递归函数

        如果一个函数在内部调用自身,则这个函数就是递归函数。递归函数有以下特点:

         1. 必须有一个明确的结束条件;

         2. 每次进入更深一层递归时,问题规模比上一次递归应有所减少;

         3. 递归执行效率不高,递归次数过多会导致内存溢出。

     1 def calc(n):
     2     print(n)
     3     if int(n/2)==0:
     4         return n
     5     res = calc(int(n/2))
     6     return res
     7 res = calc(10)
     8 print(res)
     9 
    10 """
    11 运行结果:
    12     10
    13     5
    14     2
    15     1
    16     1
    17 """

              运行过程分析:

                   

    三. 匿名函数

         匿名函数定义方法:lambda 形参:逻辑操作

         lambda函数的返回结果为该函数的地址。

    1 func = lambda x,y:(x+1,y+1)    #将匿名函数的地址重新赋值给名为func的子函数
    2 n = func(10,11)    #通过名为func的子函数获取lambda函数的运行结果:(10+1,11+1)
    3 print(n)
    4 
    5 """
    6 运行结果:(11, 12)
    7 """

    四. 高阶函数

        满足以下条件之一的函数称为高阶函数:

         1. 函数接收的参数中包含函数名

     1 def foo(n):
     2     print(n)
     3 def bar(name):
     4     print("my name is",name)
     5     return name
     6 foo(bar("alex"))
     7 
     8 """
     9 运行结果:
    10     my name is alex
    11     alex
    12 结果分析:子函数bar()的运行结果作为foo()的输入,依次调用bar()与foo()
    13 """

            2. 函数返回值中包含函数名

     1 def foo():
     2     print("from foo")
     3 def bar():
     4     print("from bar")
     5     return foo
     6 n = bar()     #通过调用函数bar()将子函数foo()的地址赋值给变量n
     7 n()     #相当于foo()
     8 
     9 """
    10 运行结果:
    11     from bar
    12     from foo
    13 """
     1 name = "alex"
     2 def bar():
     3     name = "rabin"
     4     def foo():
     5         print(name)
     6     return foo
     7 n = bar()     #通过调用函数bar()将子函数foo()的地址赋值给变量n
     8 print(n)
     9 n()     #相当于foo()
    10 
    11 """
    12 运行结果:
    13     <function bar.<locals>.foo at 0x000001CA041E16A8>
    14     rabin
    15 """
     1 def bar():
     2     name = "alex"
     3     def foo():
     4         name = "rabin"
     5         def tt():
     6             print(name)
     7         return tt
     8     return foo
     9 n = bar()     #通过调用函数bar()将子函数foo()的地址赋值给变量n
    10 print(n)
    11 m = n()      #相当于foo(),将子函数tt()的地址赋值给变量m
    12 print(m)
    13 m()     #相当于foo()
    14 
    15 """
    16 运行结果:
    17     <function bar.<locals>.foo at 0x0000021720DC76A8>
    18     <function bar.<locals>.foo.<locals>.tt at 0x0000021720DC7730>
    19     rabin
    20 """

    五.   map函数

         1. 函数调用:res = map(func,list)

         2. 函数功能描述:对list序列中每个元素进行指定的func函数功能操作,输出序列中元素个数及位置保持不变。

         3. 示例代码:

    1 num_list = [11,22,33,44,55]
    2 res = map(lambda x:x+1,num_list)
    3 print(list(res))
    4 
    5 """
    6 运行结果:[12, 23, 34, 45, 56]
    7 结果分析:对序列num_list中的每个元素值+1
    8 """

         4. 等同功能函数实现代码:

     1 num_list = [11,22,33,44,55]
     2 def map_test(func,num_list):
     3     res = []
     4     for item in num_list:
     5         a = func(item)
     6         res.append(a)
     7     return res
     8 res = map_test(lambda x:x+1,num_list)
     9 print(list(res))
    10 
    11 """
    12 运行结果:[12, 23, 34, 45, 56]
    13 结果分析:对序列num_list中的每个元素值+1
    14 """

    六. filter函

              1. 函数调用:filter(func,list)

         2. 函数功能描述:遍历筛选出list序列中所有满足func逻辑的元素。

         3. 示例代码:

    1 num_list = ["李寻欢","令狐冲","风清扬","李世民","萧峰"]
    2 res = filter(lambda x:x.startswith(""),num_list)
    3 print(list(res))
    4 
    5 """
    6 运行结果:['李寻欢', '李世民']
    7 结果分析:筛选出序列num_list中以"李"开头的元素
    8 """

         4. 等同功能函数实现代码:

     1 num_list = ["李寻欢","令狐冲","风清扬","李世民","萧峰"]
     2 def filter_test(func,num_list):
     3     res = []
     4     for item in num_list:
     5         if func(item):
     6             res.append(item)
     7     return res
     8 res = filter_test(lambda x:x.startswith(""),num_list)
     9 print(list(res))
    10 
    11 """
    12 运行结果:['李寻欢', '李世民']
    13 结果分析:筛选出序列num_list中以"李"开头的元素
    14 """

    七. reduce函数

         1. 函数调用:reduce(func,list,initial=None)

         2. 函数功能描述:对list序列中的每个元素进行func函数功能操作,输出元素个数发生变化

         3. 示例代码:

    1 from functools import reduce
    2 num_list = [11,22,33,44]
    3 res = reduce(lambda x,y:x+y,num_list)
    4 print(res)
    5 
    6 """
    7 运行结果:110
    8 结果分析:计算序列num_list中所有元素之和
    9 """

         4. 等同功能函数实现代码:

     1 num_list = [11,22,33,44]
     2 def reduce_test(func,num_list,init=None):
     3     if init is None:
     4         res = num_list.pop(0)
     5     else:
     6         res = init
     7     for item in num_list:
     8         res = func(res,item)
     9     return res
    10 res = reduce_test(lambda x,y:x+y,num_list)
    11 print(res)
    12 
    13 """
    14 运行结果:110
    15 结果分析:计算序列num_list中所有元素之和
    16 """
  • 相关阅读:
    进行C# 编写发送邮箱,报错Error: need EHLO and AUTH first !
    vue使jsZip和FileSaver.js打包下载
    基于js或vue项目实现一次批量文件下载功能
    模块
    now 与 down 中的 ow 发音是否一样?
    __time64_t 解决了 2038 年问题,可是没解决 1969年问题
    MagickSetOption(mw, "jpeg:extent", "...kb"); 这个函数有时结果出乎意料
    解决Idea启动Spring Boot很慢的问题
    CAP原理和BASE思想和ACID模型
    java并发编程之Condition
  • 原文地址:https://www.cnblogs.com/zizaijiapu/p/10387113.html
Copyright © 2020-2023  润新知