While-loop: UnboundLocalError: local variable referenced before assignment

Question:

I’m using python 3.5.

So I’m trying to create a function that takes x and y as positive float input, and then computes and returns R = x – N * y, where N is the largest integer, so that x > N * y.

I made this function:

def floatme(x,y):

     N = 1

     while x <= N * y:
         R = x - N * y
         N = N+1

     return R

but then I receive the following error, when running my function:

UnboundLocalError: local variable ‘R’ referenced before assignment

I searched around and found that this happens when an assigned variable in the function, is already assigned outside of it. But this is not the case for my function, so I do not understand why Python is complaining?

Asked By: NAstuden

||

Answers:

R is defined inside the while loop. If the condition of the while loop is not true initially, its body never executes and R is never defined. Then it is an error to try to return R.

To solve the problem, initialize R to something before entering the loop.

If not entering the loop is an error condition, i.e. the caller should not be passing in values that cause the problem to begin with, then catch the UnboundLocalError using a try/except structure and raise a more appropriate exception (such as ValueError).

Answered By: kindall

I’m afraid your code has an infinite loop with while x <= N * y: .
Value of x will never increase in the code. (perhaps you meant to use >= instead?)

That being said, you will still get UnboundLocalError even if you define R outside. You have to tell the function that it’s global.

R = None # init
def floatme(x,y):
    global R    # THIS IS THE KEY LINE
    N = 1
    while x >= N * y:   # changed to >=
        R = x - N * y
        N = N+1

    return R

At this point it’s worth noting that this function is just doing x % y if x>=y else None so I’m not sure if I get the intent here.

Answered By: Noobification

Based on @Noobification’s answer.

def floatme(x,y):
    R = None # KEY LINE
    N = 1
    while x >= N * y:   
        R = x - N * y
        N = N+1

    return R
Answered By: Wei Xu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.