我不确定为什么当我声明一个全局变量时它不起作用...
first_read = True
def main():
if (first_read == True):
print "hello world"
first_read = False
print 'outside of if statement'
if __name__ == '__main__':
main()
我的回溯显示以下错误:
Traceback (most recent call last):
File "true.py", line 12, in <module>
main()
File "true.py", line 5, in main
if (first_read == True):
UnboundLocalError: local variable 'first_read' referenced before assignment
您必须将变量定义为全局变量:
first_read = True
def main():
global first_read
if (first_read == True):
print "hello world"
first_read = False
print 'outside of if statement'
if __name__ == '__main__':
main()
我是一名优秀的程序员,十分优秀!