Search code examples
pythonpython-3.xglobal-variablesglobal

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?

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".


Solution

  • The global keyword should actually be use in a local scope to reference the global variable. 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.