0

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
WyWyGuy
  • 3
  • 3
  • Wow, this is strange. Apparently `n -= 1` line is causing the issue. But I don't know why. I want to know about this too. – Nitish Sep 15 '22 at 06:40
  • Oh really? How do you figure that? I think the while loop was the one throwing the error for me – WyWyGuy Sep 15 '22 at 14:10
  • 1
    Please see the answer to this question https://stackoverflow.com/questions/9264763/why-does-this-unboundlocalerror-occur-closure It explains "If there is an assignment to a variable inside a function, that variable is considered local". So the issue is indeed where `n -= 1` – crunker99 Sep 15 '22 at 16:56
  • This explains a lot. – Nitish Sep 20 '22 at 05:46

0 Answers0