Truncating a random gammavariate result to an upper limit
<p>I want to draw a number from a gammavariate, but I want to set an upper limit.
Why this does not work?</p>

<pre><code>import random
[int(random.gammavariate(3, 3)) if x &lt; 21 else 20 for x in range(1)]

Out[59]: [22]
</code></pre>

<p>Thanks.</p>

<p>If I've understood correctly you want to clamp a random value following the <a href="https://docs.python.org/2/library/random.html#random.gammavariate" rel="nofollow">gamma distribution</a> in a certain range [0-20], you could do it like this:</p>

<pre><code>import random


def clamp(x, min_value, max_value):
    return max(min(max_value, x), min_value)

min_value, max_value = 0, 20
print([clamp(int(random.gammavariate(3, 3)), min_value, max_value)
       for v in range(1)])
</code></pre>

<p>In your example, you were using the index x instead of your random gamma value, I'm assuming that's not what you want</p>

python random