【问题标题】:How to use a global variable in Python?如何在 Python 中使用全局变量?
【发布时间】:2019-08-19 08:19:40
【问题描述】:

我不确定为什么声明全局变量时它不起作用...

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

【问题讨论】:

标签: python


【解决方案1】:

您必须将变量定义为全局:

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()

【讨论】:

  • 只是好奇...我还声明了一个全局变量:'ntw_device = []'。但我不必指定全局 ntw_device 来使用它...这是为什么呢?列表有什么不同吗?
【解决方案2】:

def main 中你应该像这样声明一个全局变量:

global first_read

这将在主函数中使用first_read 作为全局变量。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
相关资源
最近更新 更多