zoukankan      html  css  js  c++  java
  • Python--function

    函数就是"变量".定义一个函数就是相当于将一个函数体赋值给函数名.

    一、参数的调用

    def test0(x,y,z):            #定义函数test0,形参x,y,z
      print("x=%d,y=%d,z=%d" %(x,y,z))  #依次输出形参的值
    test0(1,2,3)              #位置参数调用
    test0(x=2,z=0,y=1)           #关键字调用
    test0(2,z=1,y=3)            #位置参数与关键字调用,位置参数要在前

    -----------------------------------------------------------------------------
    x=1,y=2,z=3
    x=2,y=1,z=0
    x=2,y=3,z=1
    =============================================================================
    def test1(x,y=2):           #定义默认参数,可省略传递
      print("x=%d,y=%d" %(x,y))

    test1(1)
    -----------------------------------------------------------------------------
    x=1,y=2
    =============================================================================

    def test2(*args): #不固定形参,可传递多个位置参数,把位置参数转换成元组tuple
      print(args)
    test2(1,2,3)
    test2(*[1,2,3])
    -----------------------------------------------------------------------------
    (1, 2, 3)
    (1, 2, 3)
    =============================================================================
    def test3(**kwargs):   #将字典作为形参,可传递多个关键字参数,值为key:value
      print(kwargs)
      print(kwargs['name'])
      print(kwargs['age'])
      print(kwargs['sex'])
    test3(name='xy',age=23,sex="N")
    test3(**{'name':'xy','age':23,'sex':'N'})
    -----------------------------------------------------------------------------
    {'name': 'xy', 'age': 23, 'sex': 'N'}
    xy
    23
    N
    {'name': 'xy', 'age': 23, 'sex': 'N'}
    xy
    23
    N
    =============================================================================

    def test4(name,**kwargs):          #位置参数和字典参数传递值
      print(name,kwargs)
    test4('xy',age=23,sex='N')
    -----------------------------------------------------------------------------
    xy {'age': 23, 'sex': 'N'}
    =============================================================================
    def test5(name,age=18,**kwargs):    #传递位置参数,关键字参数,字典参数
      print(name,age,kwargs)
    test5('xy',sex='N',hobby='belle',age=23) #匹配不到形参时,参数后移至**kwargs
    -----------------------------------------------------------------------------
    xy 23 {'sex': 'N', 'hobby': 'belle'}
    =============================================================================
    def test6(name,age,*args,**kwargs):      #定义多个类型形参,tuple,字典
      print(name,age,args,kwargs)
    test6('xy',23,'python','perl',linux='shell',sql='mariadb',sex='N')

                  #依次匹配形参,传递的位置形参要在关键字形参前面
    -----------------------------------------------------------------------------
    xy 23 ('python', 'perl') {'linux': 'shell', 'sql': 'mariadb', 'sex': 'N'}
    =============================================================================

    二、函数的返回值return

      函数中return表示函数结束

      Python中的函数的返回值可以是一个参数,也可以是多个参数以元组格式返回

    def return_test():
    print("line one")
    print("line two")
    return 'hello',['nice','to','meet','you'],666     #返回多个参数
    print("line three")        #return后面不执行
    print(return_test())          #打印函数返回值
    -----------------------------------------------------------------------------

    line one
    line two
    ('hello', ['nice','to','meet','you'],666)    #返回值为元组tuple格式

    =============================================================================

     三、匿名函数

    匿名函数只能有一个表达式,不用写return,返回值就是该表达式的结果

    函数没有名字,不必担心函数名冲突

    calc = lambda x:x**3    #lambda表示匿名函数,冒号前面的x表示函数参数

    print("calc is %s" %calc(3))

    -----------------------------------------------------------------------------

    calc is 27

    =============================================================================

    四、函数内的局部变量与全局变量

    name = 'xy'    #name为全局变量
    def test7(name):            #函数内name为局部变量
      print("before change",name)
      name = "architect"        #函数内更改变量的值,函数外不会改变
      print("after change",name)    #函数内打印局部变量name的值
    test7(name)
    print(name)
    -----------------------------------------------------------------------------
    before change xy
    after change architect
    xy            #函数外的值
    =============================================================================
    school = "ahxh edu"
    def test8(name):            #全局变量不会被局部改变
      global school            #global,函数中申明全局变量,不建议更改
      school = 'xwxh edu'        #将全局变量重新赋值
      print(school)
    test8(school)
    print(school)
    -----------------------------------------------------------------------------
    xwxh edu               #函数内的值
    xwxh edu                #此处全局变量已被在函数中更改
    =============================================================================
    names_list=['xy','jack','lucy']
    def test9():      #当传递list,tuple,字典时传递的是地址,函数中可改变全局变量
      names_list[0] = 'architect'
      print("inside func",names_list)
    test9()
    print(names_list)
    -----------------------------------------------------------------------------
    inside func ['architect', 'jack', 'lucy']        #函数内的值
    ['architect', 'jack', 'lucy']              #函数外的值
    =============================================================================
    五、函数的递归
        递归约999次启动程序保护关闭进程,递归必须有明确的结束条件
        进入深一层次递归算法要减少,递归的效率不高,容易导致栈溢出
    def calc(n):
      print(n)
      return calc(n+1)                  #无限递归
    calc(0)
    -----------------------------------------------------------------------------
    996
    Traceback (most recent call last):
    File "递归.py", line 8, in <module>
    calc(0)
    File "递归.py", line 7, in calc
    return calc(n+1)
    File "递归.py", line 7, in calc
    return calc(n+1)
    File "递归.py", line 7, in calc
    return calc(n+1)
    [Previous line repeated 992 more times]
    File "递归.py", line 6, in calc
    print(n)
    RecursionError: maximum recursion depth exceeded while calling a Python object
    =============================================================================
    def calc(n):
      print(n)
      if int(n/2) ==0:
        return n
      return calc(int(n/2)) #递归调用函数
    calc(10)
    -----------------------------------------------------------------------------
    10
    5
    2
    1
    =============================================================================
    六、高阶函数

    把一个函数名当做实参传递给另外一个函数

    返回值中包含函数名 


    def add(x,y,f):             #高阶函数,函数可以传递函数
      return f(x) + f(y)

    res = add(3,-6,abs)           #abs为python内置函数,计算绝对值
    print("res=%d" %(res))
    -----------------------------------------------------------------------------
    res=9

    =============================================================================

    函数名指向函数体,将函数名传递给形参,形参共有函数体地址

     import time        #导入time模块

    def high1():
      time.sleep(3)      #睡眠3秒

    print("this is high1")
    def high2(func):
    start_time=time.time()    
    func()          #调用形参函数func(),实参是high1()
    stop_time=time.time()
    print("the func run time %s" %(stop_time-start_time)) #结束减开始时间,程序运行时间
    high2(high1)

    -----------------------------------------------------------------------------

    this is high1
    the func run time 3.015038013458252


    =============================================================================
    Python内置函数

    Built-in Functions
    abs() dict() help() min() setattr()
    all() dir() hex() next() slice()
    any() divmod() id() object() sorted()
    ascii() enumerate() input() oct() staticmethod()
    bin() eval() int() open() str()
    bool() exec() isinstance() ord() sum()
    bytearray() filter() issubclass() pow() super()
    bytes() float() iter() print() tuple()
    callable() format() len() property() type()
    chr() frozenset() list() range() vars()
    getattr() locals() repr() zip() classmethod()
    compile() globals() map() reversed() __import__()
    complex() hasattr() max() round()
    delattr() hash() memoryview() set()

     未完待续。。。

    天下古今之庸人,皆以一惰字致败,天下古今之才人,皆以一傲字致败。
  • 相关阅读:
    全文本搜索神器
    唯一索引和普通索引怎么选择
    程序员应不应该搞全栈
    c 的陷阱
    抽象能力
    电影电视剧推荐
    系统故障诊断
    一次web网站被入侵的处理记录
    Spark RDD 操作
    (转)Mysql哪些字段适合建立索引
  • 原文地址:https://www.cnblogs.com/xyhome/p/6670753.html
Copyright © 2011-2022 走看看