简体   繁体   English

全局变量-如何在引用后分配变量?

[英]global variables - how do you assign a variable after reference?

With python, the language has a useful feature which is "global", however, I saw that when experimenting with code that after I assign a global variable as an integer or value, I could use the variable but I can't change the variable after I reference it? 使用python时,该语言具有一个有用的功能,即“全局”,但是,我发现在试验代码时,在将全局变量分配为整数或值后,我可以使用该变量,但不能更改该变量我参考之后呢?

if you do not understand what i just wrote there, here is my sample code: 如果您不明白我刚才在那写的内容,请看以下示例代码:

global number
number = 5

text="hello"

if text+str(number)=="hello5":
    number=number+1

After I run this specific code I get an error, it states: 运行此特定代码后,出现错误,它指出:

UnboundLocalError: local variable 'number' referenced before assignment

If you can help please state how I can make this code run "properly". 如果可以帮助,请说明如何使此代码“正确”运行。

The global keyword should actually be use in a local scope to reference the global variable. 实际上,应该在局部范围内使用global关键字来引用全局变量。 For example 例如

c = 0
def add():
  global c
  c = c + 2

Using the global keyword in the function add(), we were able to access the variable c and change it accordingly. 使用add()函数中的global关键字,我们可以访问变量c并进行相应的更改。

Is this your full code? 这是您的完整代码吗? If so; 如果是这样的话; you'd use the 'global' command inside your functions to indicate that any reference to that variable should be taken from the global namespace rather than the local namespace, effectively allowing you to share a variable between functions without needing to pass them as parameters. 您可以在函数内部使用“全局”命令来指示对该变量的任何引用应从全局名称空间而不是本地名称空间获取,从而有效地使您可以在函数之间共享变量而无需将其作为参数传递。

Your code here is stating that the variable 'number' is global, however since 'number' has not yet been declared and assigned a value, you're getting this error. 您的代码在这里说明变量'number'是全局变量,但是由于尚未声明'number'并分配了值,因此您会收到此错误。

You only need to specify that a variable is global when you enter a different namespace (ie enter a function). 当您输入其他名称空间(即输入函数)时,只需指定变量为全局变量。 And you do this INSIDE that function, rather than upon first declaration of the variable. 然后在该函数内部执行此操作,而不是在首次声明变量时执行此操作。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM