While-loop: UnboundLocalError: local variable referenced before assignment
<p>I'm using python 3.5.</p>

<p>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.</p>

<p>I made this function:</p>

<pre><code>def floatme(x,y):

     N = 1

     while x &lt;= N * y:
         R = x - N * y
         N = N+1

     return R
</code></pre>

<p>but then I receive the following error, when running my function:</p>

<p>UnboundLocalError: local variable 'R' referenced before assignment</p>

<p>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?</p>

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

<p>To solve the problem, initialize <code>R</code> to something before entering the loop.</p>

<p>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 <code>UnboundLocalError</code> using a <code>try</code>/<code>except</code> structure and raise a more appropriate exception (such as <code>ValueError</code>).</p>

python python-3.x