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>One option would be to set <code>variable = (|variable| % (MAX - MIN + 1)) + MIN</code>. This will give you a number that is between <code>MIN</code> and <code>MAX</code>, inclusively.</p>

<p>Note that this only works consistently if <code>variable</code>, <code>MAX</code> and <code>MIN</code> are non-negative integers, and <code>MAX &gt;= MIN &gt;= 0</code>.</p>

<p>The reasoning behind this is as follows: <code>|variable| % (MAX - MIN + 1)</code> is necessarily non-negative, given that <code>MAX - MIN + 1</code> and <code>|variable|</code> are non-negative, and so the modulos must be non-negative. Thus the lowest it can be is zero. We add <code>MIN</code> after, so the number at its lowest in total can be <code>MIN</code>.</p>

<p>At most, <code>|variable| % (MAX - MIN + 1)</code> is <code>MAX - MIN</code>, due again to the nature of the modulos operator. Adding <code>MIN</code> afterwards gives us <code>MAX</code>. Thus the highest output will be <code>MAX</code>.</p>

<p>No <code>variable</code> will give a number that is lower than <code>MIN</code> or higher than <code>MAX</code>, and there is always an equal number of <code>variable</code> such that <code>n = (|variable| % (MAX - MIN + 1)) + MIN</code>, for all <code>n</code> between <code>MIN</code> and <code>MAX</code> inclusively.</p>

python