This is a problem from "Automate the boring stuff".
Write a function that uses regular expressions to make sure the password
string it is passed is strong. A strong password is defined as one that is at
least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.
How to improve this code?
if re.search('[A-Z]', password): #atleast one uppercase character
if re.search('[a-z]', password): #atleast one lowercase character
if re.search('[0-9]', password): #atleast one digit
password = input("Enter password : ")
#atleast 8 character long
if len(password) >= 8 and uppercase_check(password) and lowercase_check(password) and digit_check(password):
I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply all.
rexes = ('[A-Z]', '[a-z]', '[0-9]')
if len(password) >= 8 and all(re.search(r, password) for r in rexes)):
First, please note that this security measure has been thoroughlydebunked (although the reasons why are complex and psychological). Any code resulting from this exercise is therefore by the standards of the security community following an anti-pattern, and should not be used no matter how polished.
Rather than the
a more readable pattern is simply return something.
This code would be more scriptable if it either took passwords as arguments (using argparse) or read one password per line from standard input.
Another way to make this more scriptable is to use the really common
You preform multiple function calls which are all very related. You can cram each of the regex checks into one if statement.
You should use a main guard to ensure that the code is only running if this file is the main one, so that any programs importing this file don't have any issues.
You should also use docstrings. These allow potential documentation to display information about what the methods(s) are supposed to accomplish.
Using condensed if statements can clean up the messiness of having if: ... else: ... when there is just one statement being executed in each block.
Here is the updated code:
Ensures password has at least one uppercase, one lowercase, and one digit
return False if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password) else True
if __name__ == '__main__':
password = input("Enter password: ")
print("Strong password") if check(password) else print("Weak Password")