Python make a number loop within a range
<p>So I saw this post, <a href="http://stackoverflow.com/q/5996881/6759115">on limiting numbers,</a> but I noticed it would cut a number off if it wasn't within the range.</p>

<p>Is there a way to do this like so:</p>

<p><code>variable = 25</code></p>

<p>If your range is 1-20, can <code>variable</code> become 5?</p>

<p>Or if <code>variable = 41</code>, have it become 1?</p>

<p>I have tried this:</p>

<pre><code> def loop(number, maxn, minn):
     if number &gt; maxn:
         number = maxn - number
     return number
</code></pre>

<p>With a range of 0-20, and a number of 40, I got -20?!?</p>

<p>Loops can potentially take a long time to run. This happens when <code>maxn</code> and <code>minn</code> are close together and <code>n</code> is far from either.</p>

<p>To flat out calculate it:</p>

<pre><code>def loop(n, maxn, minn):
                    # maxn must be greater than minn
    maxn += 1       # range needed includes minn but stops just before maxn;
                    # to include maxn in the range, bump the value used up 
                    # by one.
    r = maxn - minn # get a range
    x = n - minn    # adjust so that calculations center on zero
    x = x % r       # modulo by range, 
    x = x + minn    # undo the adjustment from earlier
    return x
</code></pre>

<p>Or minimized:</p>

<pre><code>def loop(n, maxn, minn):
    return ((n - minn) % (maxn - minn + 1)) + minn
</code></pre>

python