如何在Python中使用全局变量?
我不知道为什么当我声明一个全局变量时它不起作用如何在Python中使用全局变量?,python,Python,我不知道为什么当我声明一个全局变量时它不起作用 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 recen
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
回溯(最近一次呼叫最后一次):
文件“true.py”,第12行,在
main()
文件“true.py”,第5行,在main中
如果(首次读取==真):
UnboundLocalError:赋值前引用的局部变量“first_read”
您必须将变量定义为全局变量:
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()
您必须将变量定义为全局变量:
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()
在
def main
中,应声明如下全局变量:
global first_read
这将使用
first\u read
作为main函数中的全局变量。在def main
中,您应该声明如下全局变量:
global first_read
这将使用
first\u read
作为主函数中的全局变量。可能重复的可能重复的可能重复的非常感谢!非常感谢你!只是好奇。。。我还声明了一个全局变量:“ntw_device=[]”。。但我不必指定全球ntw_设备来使用它。。。为什么呢?列表不同吗?只是好奇。。。我还声明了一个全局变量:“ntw_device=[]”。。但我不必指定全球ntw_设备来使用它。。。为什么呢?列表有什么不同吗?