How to generate random non-recurring numbers in a loop and within a range in python?
<blockquote>
  <p>Hi, I'm still a beginner and a bit lost. I'm working on a project for school that requires me to write different small programs that will 'guess' the given password. This is a bruteforce program, and I need it to guess every possible combination of 4 number passwords like those on the old iPhones. My problem is that when I use random.sample it generates the same random numbers multiple times. What function can I use, or what should I change so that the random numbers within the given range don't repeat themselves? I tried doing rand.int but it gave me "TypeError: 'int' object is not iterable"</p>
  
  <p>Additional questions: 
  - How do I get my loop to stop once n == Password4 ? It simply continues, even after the correct password is found.
  - Is there a way I can count the number of fails(n != Password4) before my success (n == Password4)?</p>
</blockquote>

<p>This is my code:</p>

<pre><code>    import random

    Password4 = 1234
    def crack_password():

while True:
    for n in (random.sample(range(1112, 10000), 1)):
        while n == Password4:
            print(n, "is the password")
            break
        if n != Password4:
            print('fail')
            break

    crack_password()
</code></pre>

<p>Update: Using a code now that does not generate random non-recurring numbers but works for the purposes I intended. Please still feel free to answer the original questions, and thank you all so much for your kindness and prompt responses.</p>

<p>New Code (credit goes to @roganjosh):</p>

<pre><code>    import datetime as dt

    Password4 = 9999

    def crack_password():
        start = dt.datetime.now()
        for n in range(10000):
            password_guess = '{0:04d}'.format(n)
            if password_guess == str(Password4):
                end = dt.datetime.now()
                print("Password found: {} in {}".format(password_guess, end - start))
                break
    guesses = crack_password()
</code></pre>

<p>You probably want to check out all possible values for a password under certain rules, e.g "4 digits" or "8 lowercase characters". Consider these answers as starting points:</p>

<ul>
<li><a href="http://stackoverflow.com/a/7074066/37020">Generating 3-letter strings with itertools.product</a> for using an alphabet and generating n-length strings</li>
<li><a href="https://docs.python.org/2/library/itertools.html#itertools.permutations" rel="nofollow">itertools.permutations</a> if you know a set of characters that don't repeat</li>
<li>If you just want to format integers with zero padding on the left (0000, 0001, ... 9999) see how to <a href="http://stackoverflow.com/a/339013/37020">accomplish that with format strings</a>.</li>
</ul>

python for-loop random while-loop range