1

Unable to bind the local x of f() to the global var x of the nested g(). Why?

def f():
 x=0
 def g():
  global x
  x+=1
  print(x)
 g()
 g() # added to make seemingly more practical 

-

>>> f()
...
NameError: global name 'x' is not defined
sof
  • 9,113
  • 16
  • 57
  • 83

2 Answers2

3

You want to make x a global variable in function f():

def f():
    global x
    x = 0
    def g():
        global x
        x += 1
        print(x)
    g()

f()
# 1


As mentioned in comment, the 'global' state of x is pointless here, so it's better you pass x as argument to g() like so:
def f():
    x = 0
    def g(x):
        x += 1
        print(x)
    g(x)

f()
# 1

This not only makes your code more concise but also removes the overhead of 'global's.

Austin
  • 25,759
  • 4
  • 25
  • 48
  • One should mention, however, that the global variable in this code is utterly pointless. This function will always print `1`, no matter the "global" state of `x` – user2390182 Sep 08 '18 at 16:46
  • i also think it's genraly good practice not to use global, unless it's necesary – Jonas Wolff Sep 08 '18 at 17:09
  • 1
    @JonasWolff Ofcourse. Here is more details to it: https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – Austin Sep 08 '18 at 17:11
0

To avoid using globals, simply pass a parameter through the function g:

def f():
    x=0
    def g(y):
        y+=1
        print(y)
    g(x)

f()

This should work.

Chandella07
  • 2,089
  • 14
  • 22
Oqhax
  • 419
  • 1
  • 4
  • 16