「Python」第一阶段第七章笔记

发布时间 2023-08-20 16:12:09作者: OrzMiku

函数的多返回值

"""
函数的多返回值
"""

def my_return():
    return 1,2

x,y = my_return()

print(x,y,type(x),type(y))

函数的多种传参方式

"""
函数的多种传参方式
 - 位置
 - 参数
 - 缺省
 - 不定长
"""

# 位置传参 形参实参位置对应
def add(a = 0,b = 0):
    print(f"a is {a}, b is {b}.")
    return a+b
print(add(114,514)) # a = 114, b = 514

# 参数传参 xxx = yyy
# 位置传参可以和参数传参,但位置传参必须在前
print(add(b=114,a=514))

# 缺省传参(默认参数)
# 设置默认值得参数必须在参数表后面
# 换句话说设置默认值得参数,后面必须没有 没设置默认值的参数
print(add(b=114514))
print(add(114514))

# 不定长传参(可变参数)
# 不确定传递多少参数
# 位置不定长
def test_1(*args): # *args不是指针(
    # args -> class tuple
    print(f"{type(args)} {args}")
# 关键字不定长
def test_2(**args): # **args不是指针的指针(
    # args -> class dict
    print(f"{type(args)} {args}")

list_test = [114,514,1919,"810"]
test_1(list_test,114,514,1919,810)
test_2(name="田所赵二",age=24)

函数作为参数

"""
函数作为参数传递
计算逻辑的传递,而非数据的传递
"""

def tell1():
    print("砸!瓦鲁多!")

def tell2():
    print("食堂破辣酱!")

def func(tell1):
    tell1() # 这个是形参,是你传入的函数,不是上面定义的tell1

func(tell1)
func(tell2)

# eg.简单计算器

def plus(a,b):
    return a + b

def subt(a,b):
    return a + b

def mult(a,b):
    return a * b

def devi(a,b):
    if b == 0:
        return None
    return a / b

def calc(func,a,b):
    print(f"结果为:{func(a,b)}")

calc(plus,114,514)
calc(subt,114,514)
calc(mult,114,514)
calc(devi,114,514)

lambda匿名函数

"""
匿名函数定义
# def关键字定义有名称的函数,可以复用
# lambda关键字定义匿名函数,只可临时使用一次
"""

# lambda定义语法
# lambda 传入参数: 函数体(一行代码)

def test_func(computer,a,b):
    print(f"结果是{computer(a,b)}")

def plus(a,b):
    return a + b;

test_func(plus,114,514)
test_func(lambda a,b : a+b,114,514)