Search code examples
pythonfunctionscopegloballocal

global statement isn't working, and I don't understand why


I'm a beginner in this area and I'm having trouble finding the same cases to my question. My code is like this:

def zerofunc(value):
      global g
      value = 0
g = 15
zerofunc(g)
print(g)

I set the g to global inside the function to produce 0 as the final result, but it still prints out 15 instead of 0. Could anybody explain why the global statement is not working in this case, and what I should do to avoid the same mistake?


Solution

  • Your function sets a variable named value to zero, leaving g untouched. If you want to change, g, this code would do it:

    def zerofunc(value):
          global g
          g = 0
    g = 15
    zerofunc(g)
    print(g)
    

    That being said, there doesn't appear to be a good reason to make g global; globals are generally discouraged.