python学习(4)-函数:lambda表达式、eval()函数、递归函数、嵌套函数

lambda表达式

注意:只允许包含一个表达式,不能包含复杂语句
语法:
lambda arg1,arg2,arg3:<表达式>

f = lambda a, b, c: a + b + c
print(f(2, 3, 4))

#等价于
def test01(a, b, c):
    return a + b + c
print(test01(2, 3, 4))

返回值:9

# lambda 表达式数组
g = [lambda a: a * 2, lambda b: b * 3, lambda c: c * 6]
print(g[0](6), g[1](3), g[2](4))

返回值:12 9 24

eval()函数

将字符串当成有效的表达式来求职并返回计算结果

s = "13+6"
a = eval(s)
print(a)

返回值为19

dict1 = dict(a=100, b=200)
#dict1作为参数传入
d = eval("a+b", dict1)
print(d)

返回值为300

递归函数

自己调自己的函数
注意:1 要有终止条件
2 把第n步的值和第n-1步相关联


def test01(n):
    print("test01:", n)
    if n == 0:  # 终止条件
        print("over")
    else:  # 递归调用
        test01(n - 1)
    print("test01end:", n)
test01(5)

返回值为:
test01: 5
test01: 4
test01: 3
test01: 2
test01: 1
test01: 0
over
test01end: 0
test01end: 1
test01end: 2
test01end: 3
test01end: 4
test01end: 5

嵌套函数

在函数内部定义的函数

def outer():
    print("outer running..")

    #只能内部使用
    def inner01():
        print("inner01 running...")

    inner01()
outer()

什么时候使用嵌套函数:
1 封装数据隐藏:外部无法访问嵌套函数
2 避免函数内部重复代码
3 闭包

nonlocal关键字

nonlocal 用来声明外层的局部变量
global 用来声明全局变量

LEGB原则

python在查找变量名称是,是按照LEGB规则查找的:
Local->Enclosed->Global->Built in
Local 函数或者类的方法内部
Enclosed 嵌套函数(一个函数包裹另外一个函数,闭包)
Global 模块中的全局变量
Built in 指的是python为自己保留的特殊名称-内置变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值