python3之函数

一、函数

实现特定单一功能的一段代码,可重复使用
函数能提高应用的模块性,和代码的重复利用率

二、函数的定义,调用,返回值

1 定义

def function_name(参数列表):
    函数体

2 调用函数

函数必须先定义再调用

function_name(参数列表)

其中
可以没有参数,()必须要有

3 函数返回值

使用return结束函数并返回零个或多个值
返回多个值时,返回的多个值会被封装成元组返回

示例

输出斐波那契数列前n项组成的列表

def Fib(n):
    if n <= 0:
        return 'n必须是大于0的整数'
    if n == 1:
        return list((0,))
    elif n == 2:
        return list((0,1))
    else:
        n1, n2 = 0, 1
        list_1 = [n1, n2]
        while len(list_1) < n:
            n1, n2 = n2, n1+n2
            list_1.append(n2)
        return list_1

[print(Fib(e)) for e in range(10) ]

三、函数的参数

函数传入的参数是number,str,tuple类型时,不会修改原来的值
若想改变参数的某些值,可以把参数包装成列表,字典等可变对象,在传入函数,在函数中通过列表,字典的方法修改

def swap_1(a,b) :
    a,b = b,a
    print('函数中a,b交换之后的值:a='+a+',b='+b)

def swap_2(list):
    list[0] = 'AAA'
    print('函数中list的元素:',list)

a='asd'
b='qwe'
print('调用函数之前a,b的值:a='+a+',b='+b)
swap_1(a,b)
print('调用函数之后a,b的值:a='+a+',b='+b)

list_1 = [11,'asd','qwe',98,'wert',99]
print('调用函数之前列表的元素:',list_1)
swap_2(list_1)
print('调用函数之后列表的元素:',list_1)

a,b经过调用函数之后,值并没有改变
列表经过调用函数之后,对应位置的元素已经改变

1 默认参数

默认参数后面不能有关键字参数,可以有个数可变的参数

def say_hello(name='marry',message='wellcome into the python3 world!' :
    print(name+",hello!"+message)

say_hello()
say_hello('jack','wellcome!')
say_hello(name='jack')
say_hello(message='wellcome!')
say_hello(name='jack',massage='wellcome!')

其中
第一次调用函数未传入参数,使用默认参数
第二次调用函数按参数位置依次传入参数,使用传入的参数
第三次到第五次,按关键字传入参数,使用传入的参数

2 关键字参数

def area(width,height) :
    return width * height

print(area(3,4))
print(area(5,height=6))
print(area(width=5,height=6))
print(area(height=6,width=5))

其中
第一个print:
按参数位置依次传入参数

第二个到第四个print: 
根据关键字传入参数
关键字可以任意调换位置,且必须位于位置参数之后,即关键字参数后面只能是关键字参数

3 个数可变的参数

3.1 多个参数当做元组传入

def test(n,*books,price) :
    print(n)
    print(books)
    print(price)
    print(type(books))    


test('c++','python','java','go','Rust',price='Price')


其中
第一个参数传给n,('python','java','go','Rust')当做元组传给参数books,参数price必须使用关键字传入
允许*books在参数列表的任何位置
位于*books前面的参数使用位置参数传参,位于*books后面的参数使用关键字参数传参

3.2 多个参数当做字典传入

def test(n,*books,price,**status) :
    print(n)
    print(books)
    print(price)
    print(type(books))   

test('c++','python','java','go','Rust',price='Price',pyton=99,java=95,go=97,Rust=98)

其中
"pyton=99,java=95,go=97,Rust=98"当做字典传给status参数
**status后面不能再有任何参数,即**status必须位与参数列表的最后

四、递归函数

函数体内调用函数本身
必须向已知方向递归

示例

阶乘

def factorial(n) :
    if n == 0 or n == 1 :
        return 1
    else :
        return n * factorial(n-1)

print(factorial(5))

五、lambda表达式

无需定义函数名的匿名函数
用户可以传入参数

格式

lambda 参数列表: 表达式

示例

lamb = lambda x, y: x*y
print(lamb(2,3))
原文地址:https://www.cnblogs.com/gudanaimei/p/13463748.html