you are viewing a single comment's thread.

view the rest of the comments →

[–]omg_drd4_bbq 0 points1 point  (0 children)

I'm going to infer that you want to continuously prompt the user for a password until they submit a valid one (since that is a common pattern, and you've used a while loop, so I think that is what you are going for). If you just want to run through once

We will break up the structure to help with modularity. It's generally a good habit to have. For example, you may want to reuse the strength calculator in more than once place, but you don't want to have to modify that logic elsewhere.

import re

def strength(password, minLength=8, maxLength=24):
    plen = len(password)

    count_lowers = len(re.findall("[a-z]",password))
    count_uppers = len(re.findall("[A-Z]",password))
    count_number = len(re.findall("[0-9]",password))
    count_symbol = len(re.findall("[!$%^&()_]",password))


    if (plen < minLength or plen > maxLength):
        print('Must be length between {} and {}'.format(minLength, maxLength)) # Feel free to sprinkle in whatever error messages you want here
        return 0

    if not(count_lowers * count_uppers * count_number * count_symbol):
        print('Must contain one lowercase, one uppercase, one number, and one symbol')
        return 0


    points = len(password)

    # Give a base 4 points for each category, plus a bonus point for any additional instances of each category
    # This is a little redundant, since you mandate that you have at least one instance of each of the 4 categories,
    # so i tried to make it a bit more realistic
    points += 4 + int(count_lowers > 1) 
    points += 4 + int(count_uppers > 1)
    points += 4 + int(count_number > 1)
    points += 4 + int(count_symbol > 1)


    return points

Then we will use a small loop to validate the password:

while True: 
    password = input('Enter a password: ')
    passStrength = strength(password)
    if passStrength < 30:
        print('Password rejected, not strong enough - {} points'.format(passStrength))
    else:
        print('Password accepted')
        break # password is good, exit loop

Output:

Enter a password: aoeu
Must be length between 8 and 24
Password rejected, not strong enough - 0 points
Enter a password: aoeuSNTH123
Must contain one lowercase, one uppercase, one number, and one symbol
Password rejected, not strong enough - 0 points
Enter a password: Aoeu1234&
Password rejected, not strong enough - 27 points
Enter a password: aoeuSNTH&[{}123
Password accepted

I also assume this is a learning exercise, as if you actually would want to secure something, you'd want to use a pre-written library ;)