Search code examples
pythonnumbersuppercaselowercasestring-length

Python - Checking an input for numbers, uppercase, lowercase letters and special characters


I am trying to create a little program in which the user enters a password into the console. The program then checks whether the password is weak, medium or strong depending what the user has typed in.

I need to check how many uppercase, lowercase and numbers have been entered and then tell the user how strong their password is.

I have most of the program completed, but since I haven't really used Python for long I am not too familiar with anything advanced, bear in mind younger people have to understand this code too who are not going to be good at coding themselves.

So far I have:

#Welcome the user to the application.
print("Hello, please enter a password to check how secure it is");

#Set a variable called MinPass and set a value of 6.
MinPass = 6;

#Set a variable called MaxPass and set a value of 12.
MaxPass = 12;

#Set variable EnteredPass and wait for user input
EnteredPass = input("Password: ");

while len(EnteredPass) < MinPass:
    print("Your password is too short, please enter a longer password and try again")
    EnteredPass = input("Password: ");

while len(EnteredPass) > MaxPass:
    print("Your password is too long, please shorten it and try again!");
    EnteredPass = input("Password: ");

Please note, this is for educational purposes only. I'm not planning on making a program in an intent to steal random password. It's for a part of a course that's going on in my school!


Solution

  • This contains a few more-advanced concepts, but should be easy enough to follow:

    import string
    
    def long_enough(pw):
        'Password must be at least 6 characters'
        return len(pw) >= 6
    
    def short_enough(pw):
        'Password cannot be more than 12 characters'
        return len(pw) <= 12
    
    def has_lowercase(pw):
        'Password must contain a lowercase letter'
        return len(set(string.ascii_lowercase).intersection(pw)) > 0
    
    def has_uppercase(pw):
        'Password must contain an uppercase letter'
        return len(set(string.ascii_uppercase).intersection(pw)) > 0
    
    def has_numeric(pw):
        'Password must contain a digit'
        return len(set(string.digits).intersection(pw)) > 0
    
    def has_special(pw):
        'Password must contain a special character'
        return len(set(string.punctuation).intersection(pw)) > 0
    
    def test_password(pw, tests=[long_enough, short_enough, has_lowercase, has_uppercase, has_numeric, has_special]):
        for test in tests:
            if not test(pw):
                print(test.__doc__)
                return False
        return True
    
    def main():
        pw = input('Please enter a test password:')
        if test_password(pw):
            print('That is a good password!')
    
    if __name__=="__main__":
        main()