1
回答
python局部变量和全局变量的问题
注册华为云得mate10,2.9折抢先购!>>>   
fengfeng@fengfeng-Lenovo-XiaoXin-700-15ISK:~$ cat -n test1.py
     1    a = 1
     2    def do_something():
     3        print a
     4    
     5    do_something()
fengfeng@fengfeng-Lenovo-XiaoXin-700-15ISK:~$ python test1.py
1
fengfeng@fengfeng-Lenovo-XiaoXin-700-15ISK:~$ cat -n test2.py
     1    a = 1
     2    def do_something():
     3        print a
     4        a = 3
     5    
     6    do_something()
fengfeng@fengfeng-Lenovo-XiaoXin-700-15ISK:~$ python test2.py
Traceback (most recent call last):
  File "test2.py", line 6, in <module>
    do_something()
  File "test2.py", line 3, in do_something
    print a

UnboundLocalError: local variable 'a' referenced before assignment

为什么test2.py给a赋了一个值就出错了呢?

举报
咧咧976
发帖于2年前 1回/114阅
顶部