-4
def outside(x=1):
  def printHam():
    x = x+1
    print x
  return printHam

myfunc = outside(7)
myfunc()

This doesn't works gives error Local variable referenced before assignment error python

However this works

def outside(x=1):
   def printHam():
     print x + 1
   return printHam

myfunc = outside(7)
myfunc()
Sumit
  • 486
  • 4
  • 16

1 Answers1

2

Because you are assigning x in the first case, python will assume x is a local variable (which is the default). In the second case you aren't assigning it so it will check the global scope.

If you want this example to work, you have to pass the outer x into the inner function like so:

def outside(x=1):
  def printHam(x=x):
    x = x+1
    print x
  return printHam

That being said, this seems like a horribly contrived use case, so there's probably a better solution for your actual use case. But I can't tell you what it is without knowing more about what you're trying to do.

Chad S.
  • 6,252
  • 15
  • 25