无法从python中的函数增加全局变量 [英] Can not increment global variable from function in python
本文介绍了无法从python中的函数增加全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
在函数中使用全局变量除了创建它们的那个
我有以下脚本:
COUNT = 0
def increment():
COUNT = COUNT+1
increment()
print COUNT
我只想增加全局变量 COUNT,但这给了我以下错误:
I just want to increment global variable COUNT, but this gives me the following error:
Traceback (most recent call last):
File "test.py", line 6, in <module>
increment()
File "test.py", line 4, in increment
COUNT = COUNT+1
UnboundLocalError: local variable 'COUNT' referenced before assignment
为什么会这样?
推荐答案
它是一个全局变量,所以这样做:
its a global variable so do this :
COUNT = 0
def increment():
global COUNT
COUNT = COUNT+1
increment()
print COUNT
可以在不声明全局的情况下访问全局变量,但是如果您要更改它们的值,则需要全局声明.
Global variables can be accessed without declaring the global but if you are going to change their values the global declaration is required.
这篇关于无法从python中的函数增加全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文