I am completing a project for school and am wondering what I did wrong in this code.
In Python, parameters passed through more nested functions should be able to be referenced, but the n parameter is not able to be compared to 0 in myFunc2, the error "local variable referenced before assignment." The doctests included show that, for example, it should run cycle(f1, f2, f3) with add1, times2, and add3 (which work just fine), run myFunc(n) with 0 passed as n, and myFunc2(x) with 5 passed as x. (Also works fine) I'm just curious why the n parameter doesn't seem to be coming through?
I was able to find a work around where I just make a global variable and use it in place of n and that solved the issue, but my goal is to understand where I went wrong.
def cycle(f1, f2, f3):
def myFunc(n):
def myFunc2(x):
while n > 0:
if n > 0:
x = f1(x)
n -= 1
if n > 0:
x = f2(x)
n -= 1
if n > 0:
x = f3(x)
n -= 1
return x
return myFunc2
return myFunc
>>> def add1(x):
... return x + 1
>>> def times2(x):
... return x * 2
>>> def add3(x):
... return x + 3
>>> my_cycle = cycle(add1, times2, add3)
>>> identity = my_cycle(0)
>>> identity(5)
5
>>> add_one_then_double = my_cycle(2)
>>> add_one_then_double(1)
4
>>> do_all_functions = my_cycle(3)
>>> do_all_functions(2)
9
>>> do_more_than_a_cycle = my_cycle(4)
>>> do_more_than_a_cycle(2)
10
>>> do_two_cycles = my_cycle(6)
>>> do_two_cycles(1)
19