七 Python def函数

七 Python 函数

1. 介绍:

将一些已经实现功能的代码封装起来,方便其它程序可以调用的叫做函数;

函数基本格式:

def test1(): # 定义函数
	pass # 函数体

test1()  # 调用函数

2. 函数基础

2-1. 常用用法参考:

  1. 9 9乘法表
def multi_table():
    for i in range(1,10):
        for j in range(1,i+1):
            print("{}*{}={}".format(j,i,(j*i)),end=" ")
        print("")

if __name__ == '__main__':
    # 调用 尽量 写完函数体后 再统一调用
    multi_table()
    • return 典形用法
      1-1.
def new_year():
    dis_new_year = 36
    print("距离元旦还有:{}".format(dis_new_year))
    return dis_new_year

def spring_fes(dis_new_year):
    dis_spring_fes = dis_new_year + 24
    print("距离春节还有:{}".format(dis_spring_fes))

# return 返回值 注意 有返回 就要有接收
new_years = new_year()
spring_fes(new_years)

1-2.

def test6():
    a = 1
    b = 2
    c = 3
    return [a,b,c]
    # return b
    # return c

a,b,c = test6() # () []
print(a,b,c)
  1. 函数直接输出字典
def test4(**kwargs):
    # 字典
    print(kwargs)

test4(a=1,b=2,c=3)
  1. 函数的传参
    4-1
python
def test5(a,b,c):
    print(a,b,c)

tu = (1,2,3)
test5(*tu)# 结果 1 2 3

tips: ‘*’ 不能丢
4-2

def test2(a,b=2):
    a = a + b
    print(a,b)

a = 1
test2(a) #结果 3 2

3. 函数进阶

3-1. 闭包

def test(number):
    print("--1--")
    def test_in(number_in): # 内函数
        print(number_in)
        print("--2--")
        return number_in + number   # 外函数的临时变量
    print("--3--")
    return test_in  # 外函数的返回值是内函数的引用

res = test(20)  # res = test_in
print(res(25))
'''结果:
--1--
--3--
25
--2--
45'''

3-2. 递归函数

def nums(num):
    if num > 1:
        return num*nums(num-1)
    else:
        return 1
# 6*5*4*3*2*1*num(0)
res = nums(6)
print(res) # 输出结果:6*5*4*3*2*1 = 720

tips:

  1. 调用自身的函数
  2. 递归可以做到的循环同样可以做到
  3. 设置结束条件
  4. 递归少用,效率很低

3-3. 函数嵌套

逻辑及执行顺序参考

def test():
    print('---5---')

def test2():
    print("---3---")
    test()
    print("---4---")

def test3():
    print("---1---")
    test2()
    print("---2---")

test3() # 输出结果为 1 3 5 4 2

3-4. 函数作用域

3-5. 内置函数(高阶 :reduce,filter,map)

3-5-1. reduce

3-5-1-1. 作用

reduce 函数可以对序列中元素进行累加

3-5-1-2. 用法
from functools import reduce

def multi(x,y):
    return x*y
print(reduce(multi,range(1,7))) # [1,2,3,4,5,6]
#输出结果为 720

tips: 内置函数,需要导入

3-5-2. filter函数

3-5-2-1. 作用:

能够实现过滤的效果

3-5-2-1. 用法:

实现返回1-10的奇数列表

# range 用法实现
li = []
for i in range(1,11,2):
    # print(i)
    li.append(i)
print(li)
#range 用法实现2
li = []
for i in range(1,11):
    # print(i)
    if i%2 == 1:
        li.append(i)
print(li)
#filter用法实现
def is_odd(n):
    return n % 2==1

n = range(1,10) # [1,2,3...9]
print(list(filter(is_odd,n)))
# 输出结果均为 [1,3,5,7,9]

3-5-3. map函数

pass

3-6 匿名函数(lambda)

lambda x,y:x*y
lambda 定义参数:执行体

3-6-1. 作用:

无需重复调用的函数,可以使用匿名函数;

3-6-2. 用法:

  1. 基本用法:
f = lambda x,y:x*y
print(f(5,6)) #输出结果为 30
def multi(x,y):
    return x*y
from functools import reduce
print(reduce(lambda x,y:x*y,range(1,7))) # 输出结果为:720
  1. 匿名函数作为返回值
def f(i,j):
    return lambda :i+j

res = f(6,6) # res = lambda :i+j
print(res()) # 输出结果为12
  1. 函数作为参数传递
def test(a,b,func):
    res = func(a,b) # res = lambda x,y:x+y
    return res

res = test(11,22,lambda x,y:x+y)
print(res) # 输出结果为:33

3-6-3. 补充

  1. 函数只有在被调用的时候才会执行
res = [lambda x:x+i for i in range(10)]
print(res) # 执行会出现其它字符
print(res[9](10)) #输出结果为 19 (因为调用了)
  1. i 随着 for 循环变动
res1 = [lambda x,i=i:x+i for i in range(10)]
print(res1[2](10)) # 输出结果为12

3-7. 装饰器

@函数体

作用:

在不改变函数的源代码情况下,为该函数添加新的功能

用法:

  1. 常见用法
def calcu_time(func):
    def test_in():
        start = time.time()
        func()
        end = time.time()
        print("花了{}".format(end - start))
    return test_in

@calcu_time #  test2 = calcu_time(test2)
def test2():
    print("----1----")
    time.sleep(1)

# res = calcu_time(test2) # test2 = test_in
# res() # test2() test_in()
test2()
  1. 在原有的基础上,又添加了需要传入的参数
def outer(flag):
    def calcu_time(func):
        def test_in():
            start = time.time()
            func()
            end = time.time()
            print("花了{}".format(end - start))
            if flag == 'true':
                print("正在验证")
        return test_in
    return calcu_time

@outer(flag="true") # calcu_time = outer()  test2 = calcu_time(test2)
def test2():
    print("----1----")
    time.sleep(1)
test2()

tips:

  1. 位置参数 一一对应
    sum_nums(n2,n1)
    关键字参数 不受位置的影响
    sum_nums(num2=n2,num1=n1)
发布了27 篇原创文章 · 获赞 11 · 访问量 1488

猜你喜欢

转载自blog.csdn.net/weixin_45550881/article/details/103384869