python嵌套函数例子-python3的嵌套函数

背景

最近在学python3

嵌套函数

顾名思义,即使在函数中还有函数,实现了函数的多级嵌套

def test1():

age = 10

print(age)

def test2():

te = 5

print(age)

def test3():

print(te)

test3()

test1()

输出结果:

10

test2()方法没有被执行,这是因为任意函数在定义完成之后,需要通过函数名来进行引用调用,如果没有调用,那么该函数永远不会执行。

def test1():

age = 10

print(age)

def test2():

te = 5

print(age)

def test3():

print(te)

test3()

test2()

test1()

输出结果:

10

10

5

还拿上面的例子进行学习。在嵌套函数内部,函数引用变量的时候是一层一层的向外找,同时需要注意代码的上下顺序,被调用的变量不能在调用函数的下方定义

age = 18

def func1():

# age = 20 放在上面

def func2():

print(age)

age = 20 #放在下面,其实都是放在func2的上面

func2()

func1()

输出结果:

Traceback (most recent call last):

File "嵌套函数.py", line 13, in

func1()

File "嵌套函数.py", line 10, in func1

func2()

File "嵌套函数.py", line 8, in func2

print(age)

NameError: free variable "age" referenced before assignment in enclosing scope

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值