(五)函数

函数的return:

1.函数里如果没有return,会默认返回一个None

2.函数如果return多个对象,那么会把多个对象封装成一个元组返回

3.函数遇到return,就结束了,后面的语句将不执行。

函数的作用:

1.减少重复代码

2.方便维护,更易扩展

3.保持代码一致性

函数的参数

形参与实参

def test(a,b):
    print(a,b)
test(1,2)

a,b为形参 1,2为实参 形参只有在被调用时才分配内存,在调用结束时即刻释放所分配的内存,因此形参只有在函数内部有效

参数的几种类型

①位置参数,必须一一对应,缺一不行多一也不行 

 test(1,2,3)

②关键字参数,无须一一对应,缺一不行多一也不行 

test(y=1,x=3,z=4)

③默认参数,可传可不传

def test(a,b,c=1):
    print(a,b,c)
test(1,2)
结果:1 2 1

④参数组

def test(x,*args,**kwargs):  //*args是无命名参数,放在左边,最终会做成元组;**kwargs是有命名参数(键值对),放在右边,最终会做成字典
    print(x)
    print(args)
    print(kwargs)
test(1,2,3,4,5,a = 1,b = 2)
test(1,*[2,3,4],**{'a':1})
结果:1
   (2, 3, 4, 5)
   {'a': 1, 'b': 2}
   1
   (2, 3, 4)
   {'a': 1}

大原则:位置参数必须在关键字参数的左边,*args就是把多余的位置参数放在一个元组里,**kwargs就是把关键字参数放在一个字典里

全局变量与局部变量(全局变量变量名大写;局部变量变量名小写)

无global关键字的情况:优先读取局部变量,能读取全局变量,但无法对全局变量重新赋值

name = 'xulan'  //全局变量
def test():
    print(name)
test()
结果:xulan
name = 'xulan'
def test():
    name = 'aaa'  //局部变量
    print(name)
test()
结果:aaa
name = 'xulan'
def test():
    name = 'aaa'
    print(name)
test()
print(name)
结果:aaa
   xulan

但是对于可变类型,可以对内部元素进行操作

name = ['a','b']
def test():
    name.append('c')
    print(name)
test()
print(name)
结果:['a', 'b', 'c']
   ['a', 'b', 'c']

有global关键字的情况:变量本质上就是全局的那个变量,可读取可赋值

name = ['a','b']
def test():
    global name
    name = 123
    print(name)
test()
print(name)

结果:123
   123

函数的嵌套(#为执行顺序)

NAME = 'ABC'         #1
def a():
    name = 'a'       #3
    print(name)      #4
    def b():
        name = 'b'   #6
        print(name)  #7
    b()              #5
    print(name)      #8
a()                  #2

结果: a b a
name = 'ABC'         
def a():
    name = 'a'      
    def b():
        global name
        name = 'b'   
    b()              
    print(name)      ---- a,这里不是b,b()函数改变的是全局变量,这里还是a()函数的局部变量name = 'a'
print(name) ---- ABC 
a()
print(name) ---- b
结果:ABC
   a
   b

nonlocal,指定上一级变量,如果没有就继续往上直到找到为止

name = 'ABC'
def a():
    name = 'a'
    def b():
        nonlocal name
        name = 'b'
    b()
    print(name)    ----b,a()函数中的局部变量被b()函数修改
print(name)  ---- ABC
a()
print(name)  ---- ABC,全局变量并未修改

结果:ABC
   b
   ABC

 函数的作用域

函数的作用域只跟函数声明时定义的作用域有关,跟函数的调用位置无任何关系

name='aaa'
def foo():
    name='bbb'
    def bar():
        name='ccc'
        def tt():
            print(name)
        return tt()
    return bar()
foo()
结果:ccc

 高阶函数

函数接收的参数是一个函数名,或返回值中包含函数,这样的函数称为高阶函数

def test(n):
    print(n)
def aaa(name):
    print('my name is %s'%name)
test(aaa)
test(aaa('xulan'))
结果:<function aaa at 0x0000000000A77048>
   my name is xulan
   None --因为aaa函数没有返回值,所以这里为None
def test1():
    print('from test1')
def test2():
    print('from test2')
    return test1()
res = test2()
print(res)
结果:from test2
   from test1
   None --因为test1函数没有返回值,所以这里为None
原文地址:https://www.cnblogs.com/xulan0922/p/9136647.html