'Why the local variable problem happens in python
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(increment,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(increment, 5)
b = a(1)
Solution 1:[1]
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)
Solution 2:[2]
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.
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Keith |
| Solution 2 | vladko312 |
| Solution 3 | ouflak |
