Rafael Gonzalez
Rafael Gonzalez

Reputation: 11

UnboundLocalError: local variable 'n' referenced before assignment in function

I have to create a function that will find the smallest m for which n is an integer. n=(r/(R-r))*m

I keep getting the error: local variable 'n' referenced before assignment. I tried using global n at the beginning of my function but then I get error : name 'n' is not defined Help would be much appreciated. Thank you. Here is my code:

def courbeFerme(R,r):
    global n
    if (R in range(0,1000)) and (r in range(0,1000)):
        m=0
        while ((r/(R-r))*m).is_integer()==False: 
            m+=1
            n=(r/(R-r))*m           
        return n

Upvotes: 0

Views: 925

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155507

If your while loop's conditional fails on the first test, you never assign to n, but you still try to return it. You need to either:

  1. Ensure that assignment always occurs at least once, or
  2. Give n a default value at global scope, so it has something to read even if you don't assign to it in the function.

If it's not to be a global, the same solution applies, but you have to give it a default value on entry to the function.

Upvotes: 3

Related Questions