Search code examples
pythonpassword-generator

generating a 8 character password including lower case and upper case and numbers using python


i want generate password including lower case and upper case and numbers using python but it should guarantee that all these 3 kinds has been used. so far i wrote this but it does not guarantee that all 3 kinds of characters are being used. i want divide the 8 character to 2 part. first 3 and last 5. then make sure in the firs part all 3 kinds of character are being used then shuffle them with the next part but i dont know how to code that.

import random
a = 0
password = ''
while a < 8:
    if random.randint(0, 61) < 10:
        password += chr(random.randint(48, 57))
    elif 10<random.randint(0, 61)<36:
        password += chr(random.randint(65, 90))
    else:
        password += chr(random.randint(97, 122))
    a += 1
print(password)

Solution

  • Your question consists of 3 parts:

    1. divide the 8 character to 2 part - first 3 and last 5 - (string slicing)
    2. make sure in the first part all 3 kinds of character are being used (validating passwords)
    3. shuffle the characters (shuffling strings)

    Part1: slicing strings

    Here's a good tutorial teaching how to slice strings using python..

    In your case, if you insert this at the end of your code...

    print(password[:3])
    print(password[3:])
    

    ... you'll see the first 3 chars and the last 5.


    Part2: validating passwords

    A good answer can be found here.

    def password_check(password):
        # calculating the length
        length_error = len(password) < 8
    
        # searching for digits
        digit_error = re.search(r"\d", password) is None
    
        # searching for uppercase
        uppercase_error = re.search(r"[A-Z]", password) is None
    
        # searching for lowercase
        lowercase_error = re.search(r"[a-z]", password) is None
    
         # overall result
        password_ok = not ( length_error or digit_error or uppercase_error or lowercase_error)
    
        return password_ok
    
    password_check(password) 
    

    This function will return True if satisfies all conditions, and False if not.


    Part3: shuffling strings

    if password_check(password) == True:
        new_pwd = ''.join(random.sample(password,len(password)))
        print new_pwd
    

    This code will shuffle the whole password and assign it to a new variable called new_pwd


    ps. The whole code can be found here!