- ·上一篇文章:Python3 迭代器与生成器
- ·下一篇文章:Python3 数据结构
Python3 函数
bin/python3def outer():
num = 10def inner():
nonlocal num
# nonlocal关键字声明num = 100print(num)inner()print(num)outer()以上实例输出结果:100100另外有一种特殊情况,假设下面这段代码被运行:实例(Python 3.0+)
#!/usr/bin/python3a = 10def test():
a = a + 1print(a)test()以上程序执行,报错信息如下:Traceback (most recent call last):
File "test.py", line 7, in <module> test() File "test.py", line 5, in test a = a + 1UnboundLocalError:
local variable 'a' referenced before assignment错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改。修改 a 为全局变量,通过函数参数传递,可以正常执行输出结果为:实例(Python 3.0+)
#!/usr/bin/python3a = 10def test(a):
a = a + 1print(a)test(a)执行输出结果为:11
num = 10def inner():
nonlocal num
# nonlocal关键字声明num = 100print(num)inner()print(num)outer()以上实例输出结果:100100另外有一种特殊情况,假设下面这段代码被运行:实例(Python 3.0+)
#!/usr/bin/python3a = 10def test():
a = a + 1print(a)test()以上程序执行,报错信息如下:Traceback (most recent call last):
File "test.py", line 7, in <module> test() File "test.py", line 5, in test a = a + 1UnboundLocalError:
local variable 'a' referenced before assignment错误信息为局部作用域引用错误,因为 test 函数中的 a 使用的是局部,未定义,无法修改。修改 a 为全局变量,通过函数参数传递,可以正常执行输出结果为:实例(Python 3.0+)
#!/usr/bin/python3a = 10def test(a):
a = a + 1print(a)test(a)执行输出结果为:11
Python3 函数