全局变量 与 局部变量

定义了一个全局变量
​​​arr = []​

在方法内使用时:

def main():
if len(arr) == 0:
f = open('log.txt','r')
arr = list(f.readlines())
f.close()

这样报错:

Traceback (most recent call last):
File "select.py", line 272, in <module>
main()
File "select.py", line 33, in main
if len(arr) == 0:
UnboundLocalError: local variable 'arr' referenced before assignment

改一下:

def main():
if len(arr) == 0:
global arr
f = open('log.txt','r')
arr = list(f.readlines())
f.close()

结果还是报错:

  File "select.py", line 34
global arr
^
SyntaxError: name 'arr' is used prior to global declaration

继续改:

def main():
global arr
if len(arr) == 0:
f = open('log.txt','r')
arr = list(f.readlines())
f.close()

终于OK了