A scope is a textual region of a Python program where a namespace is directly accessible. "Directly accessible" here means that an unqualified reference to a name attempts to find the name in the namespace.
>>>ifTrue:... msg ='I am from Runoob'...>>> msg
'I am from Runoob'>>>
实例中 msg 变量定义在 if 语句块中,但外部还是可以访问的。
如果将 msg 定义在函数中,则它就是局部变量,外部不能访问:
>>>def test():... msg_inner ='I am from Runoob'...>>> msg_inner
Traceback(most recent call last):File"<stdin>", line 1,in<module>NameError: name 'msg_inner'isnotdefined>>>
defouter():
num = 10 definner():
nonlocalnum# nonlocal关键字声明 num = 100 print(num) inner() print(num) outer()
以上实例输出结果:
100100
另外有一种特殊情况,假设下面这段代码被运行:
#!/usr/bin/python3
a = 10 deftest():
a = a + 1 print(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 为全局变量:
#!/usr/bin/python3
a = 10 deftest():
globala a = a + 1 print(a) test()