Reputation: 127
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?
Upvotes: 2
Views: 8254
Reputation: 319
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.
Upvotes: 1
Reputation: 184201
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
).
Upvotes: 2