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>Huh. A few flaws (or at least unclear spots) in your code.</p>

<ol>
<li><p>You run your loop max 257000 times. Even though the probability is low, there is a chance that you don't hit the number you seek in the loop.</p></li>
<li><p>Move your <code>import</code> statements out of your loop, no need to have python check loaded modules each round.</p></li>
<li><p>You use a generator for choices of a list (<code>randrange</code>) where you can simply use a <code>randint()</code> call.</p></li>
<li><p>You define a closed function within your loop which creates a new function at a new memory address each round.</p></li>
<li><p>You slice your results into lists of 10 elements each; is this for printing, or do you actually need your random integers grouped into such lists?</p></li>
</ol>

<p>A very simple and straightforward implementation of your described problem could be:</p>

<pre><code>import random
num = 0 # Our counter
certain_number = 123456 # The number we seek

while True: # Run until we break
    # Increment for each new step
    num += 1

    # Generate a single number from the given range
    random_number = random.randint(1, 257000)

    if random_number == certain_number:
        # Break if we hit it
        break

print('Hit after {} tries.'.format(num))

&gt;&gt;&gt; Hit after 382001 tries.
</code></pre>

python python-2.7 loops random