Alex H Alex H - 3 months ago 19
Python Question

How to generate random non-recurring numbers in a loop and within a range in python?

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 but it gave me "TypeError: 'int' object is not iterable"

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)?

This is my 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")
if n != Password4:


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.

New Code (credit goes to @roganjosh):

import datetime as dt

Password4 = 9999

def crack_password():
start =
for n in range(10000):
password_guess = '{0:04d}'.format(n)
if password_guess == str(Password4):
end =
print("Password found: {} in {}".format(password_guess, end - start))
guesses = crack_password()


If you really want to try all passwords in random order. this is more easily accomplished by

import random
digits = [str(i) for i in range(10)]
s = [''.join([a,b,c,d]) for a in digits for b in digits for c in digits for d in digits]
real_password = '1234'
i = 0
for code in s:
    if code == real_password:
        print('The password is: ', code)
        i += 1
        print(i, ' failures', end='\r')