I am trying to create a password generator in Python that must contain an uppercase letter, lowercase letter, and a number, and must have a length between 6 and 20 characters.
import random
import string
def password_gen():
while True:
length = random.randint(6,20)
pwd = []
for i in range(length):
prob = random.random()
if prob < 0.34:
char = random.choice(string.ascii_lowercase)
pwd.append(char)
elif prob < 0.67:
char = random.choice(string.ascii_uppercase)
pwd.append(char)
else:
char = str(random.randint(0,9))
pwd.append(char)
pwd = ''.join(pwd)
#check password here
return pwd
However, I am having trouble checking the password to make sure it contains the required characters listed earlier. I am not sure if/how i would use a continue statement.Any help would be greatly appreciated!
I think this would be a bit easier to ensure you meet the base requirements if you just handle those upfront.
import random
import string
def generate_pw():
length = random.randint(6,20) - 3
pwd = []
pwd.append(random.choice(string.ascii_lowercase))
pwd.append(random.choice(string.ascii_uppercase))
pwd.append(str(random.randint(0,9)))
# fill out the rest of the characters
# using whatever algorithm you want
# for the next "length" characters
random.shuffle(pwd)
return ''.join(pwd)
This will ensure your password has the characters you need. For the rest of the characters you could for example just use a list of all alphanumeric characters and call random.choice
length
times.