Home > front end >  why the local veriable problem happens in python
why the local veriable problem happens in python

Time:02-11

I got this error

increment = lambda x : x   1

def make_repeater(h, n):
    def f(x):
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f
 
    a = make_repeater(increament,5)
    b = a(1)

UnboundLocalError: local variable 'n' referenced before assignment

while when I write like this , it runs well

increment = lambda x : x   1

def make_repeater(h, n):
    def f(x):
        i = n
        value = x
        while i > 0 :
            value = h(value)
            i = i - 1

        return value
    return f
 
    a = make_repeater(increament,5)
    b = a(1)

CodePudding user response:

You can use the nonlocal keyword to refer to a variable in the nearest enclosing scope. The following code, with that change, works.


increment = lambda x : x   1

def make_repeater(h, n):
    def f(x):
        nonlocal n  # <-- added this
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

a = make_repeater(increment,5)
b = a(1)

CodePudding user response:

Your function f is not getting n as an argument.

Instead, n is taken from the scope of make_repeater.

As a result, in first example you work with variable n that is defined when the function is created, but is not availiable when the function is called.

In your second example n is used only during creation of the function, but when it is called it just uses the variable i and value 5.

CodePudding user response:

In python, if a variable in a function has the same name as a global variable, when changing the value of that variable, it will become a local variable. So the reference before the assignment problem will happen.

  • Related