1

this is what I have done as loop:

def cont_frac(k):

    n=1

    tempk=k
    x=0
    D=2.0

    if k<1:
        print("Invalid Input")
    else:
        while tempk>1:
            n=n+2
            tempk=tempk-1

        while(k>=1):
            N=n*n
            x=N/(D+x)
            n=n-2
            k=k-1

this is what I have done as recursively

n=1

k=int(input("enter the value of k:"))

p=k

def n_inc(tempk):

    while tempk>1:

        n=n+2

        tempk=tempk-1

    return n

def conts_frac(k):
    x=0

    D=2.0

    if k<1:
        print("invalid Input")
    else:
        n_inc(p)
        N=n*n
        x=N/(D+x)
        n=n-2
    return conts_frac(k-1)


conts_frac(k)

Now question is why this error UnboundLocalError is occurring in recursion part?

UnboundLocalError: local variable 'n' referenced before assignment
R Nar
  • 5,465
  • 1
  • 16
  • 32
Jordan
  • 505
  • 5
  • 13
  • because you declare `n` in the global scope and so when you do something like `n=n-2` inside of a function, it is attempting to assign `n = n-2`, that is trying to assign `n` as a local variable since globals are not implicitly included in the scope of a method definition. – R Nar Dec 03 '15 at 17:16
  • So should I declare n in function method(n_inc)? to remove this error. Sorry I am a new to programming so I am a little bit confused. – Jordan Dec 03 '15 at 17:19
  • 1
    Possible duplicate of [Python variable scope error](http://stackoverflow.com/questions/370357/python-variable-scope-error) – GingerPlusPlus Dec 03 '15 at 20:13
  • [UnboundLocalError in Python](http://stackoverflow.com/questions/9264763/unboundlocalerror-in-python) – GingerPlusPlus Dec 03 '15 at 20:14

1 Answers1

1

You are getting this error because you are mixing up global and local variables. You can solve fix this by utilizing a main(). In general having anything outside of a function definition other than import statements is bad practice.

Basically when you define a variable outside of a function, you define it for the entirety of the program. When you define a variable inside of a function, you define it only for that function, and cannot be referenced outside of the function. Where and when a variable can be used is called its scope.

You defined n as a global variable here:

n = 1

Then later redefined it in n_inc as a local variable

n = n + 2

This means n is now a local variable and you cannot use it in conts_frac. You can fix this by renaming variables, implementing a main function, or adjusting your function parameters to use n. I hope this help and wish you the best of luck Mirza!

Edit: I just noticed someone commented pointed this out. I hope this at least helps clarify what he meant.

mmghu
  • 595
  • 4
  • 15