当前位置:K88软件开发文章中心编程语言PythonPython01 → 文章内容

Python3 函数

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-10 11:00:09

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

上一页  [1] [2] [3] 


Python3 函数