-4
votes
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()
1
Search for any of the thousands of "local variable referenced before assignment" questions on this site. - BrenBarn
Even a trivial query gets 861 results: stackoverflow.com/… Did you do any research at all? - jonrsharpe
@BrenBarn i still dont get it - Sumit
someone needs to close this a duplicate. - Luke Borowy
possible duplicate of Python variable scope error - Luke Borowy

1 Answers

2
votes

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.