尽管全局声明变量,但Python中的UnboundLocalError

时间:2015-06-11 22:48:59

标签: python python-2.7

我试图在函数内部使用全局变量,尽管全局声明变量并初始化其值,但我得到以下错误:

Traceback (most recent call last):
 File "test.py", line 11, in <module>
  main()
 File "test.py", line 8, in main
  func_check()
 File "test.py", line 5, in func_check
  value += 45
UnboundLocalError: local variable 'value' referenced before assignment

以下是代码段:

value = 0
def func_check():
    value += 45

def main():
    func_check()

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

修改func_check

def func_check():
    global value
    value += 45