NAstuden - 1 year ago 119

Python 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?

Answer Source

`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.