How to use a global variable in Python?
我不知道当我声明一个全局变量时为什么它不起作用…
1 2 3 4 5 6 7 8 9 10 11 12 | 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
main() File"true.py", line 5, in main
if (first_read == True): UnboundLocalError: local variable 'first_read' referenced before assignment
在
1 | global first_read |
这将在主函数中使用
您必须将变量定义为全局变量:
1 2 3 4 5 6 7 8 9 10 11 12 | 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() |