How can I make this loop stop at a certain variable occurs
<p>I need to write a script that generates random numbers between 1-257000 and stops when a certain number occurs telling me how many numbers it generated so far.</p>

<p>i manged to get this far but can't seem to get it to stop or count</p>

<pre><code>x=1
while x &lt; 257000:
    import itertools
    import random

    def random_gen(low, high):
        while True:
            yield random.randrange(1, 257000)

    gen = random_gen(1, 100)
    items = list(itertools.islice(gen, 10))

    print items
    x = x+1
</code></pre>

<p>Thank you so much for your help </p>

<p>First, put your <code>import</code> statements and your function definitons <em>outside</em> your while-loop. That's being <strong>super</strong> redundant.</p>

<pre><code>&gt;&gt;&gt; def random_gen(low,high):
...   while True:
...     yield random.randrange(low,high)
... 
&gt;&gt;&gt; lucky = 7
&gt;&gt;&gt; rg = random_gen()   
&gt;&gt;&gt; rg = random_gen(1,1000)                 
&gt;&gt;&gt; next(itertools.dropwhile(lambda t: t[1] != lucky, enumerate(rg, 1)))
(811, 7)
&gt;&gt;&gt; 
</code></pre>

<p>Here's another run, just for fun:</p>

<pre><code>&gt;&gt;&gt; rg = random_gen(1,257000)
&gt;&gt;&gt; n,L = next(itertools.dropwhile(lambda t: t[1] != lucky, enumerate(rg, 1)))
&gt;&gt;&gt; n
22602
&gt;&gt;&gt; L
7
&gt;&gt;&gt;
</code></pre>

python python-2.7 loops random