Sep-24-2021, 06:49 PM
(This post was last modified: Sep-24-2021, 06:49 PM by deanhystad.)
Since people are submitting solutions now, I thought I might demonstrate a different approach. This is a pass/fail implementation with feedback. Get comfortable with Python exceptions. They are very useful.
def set_password(password): if len(password) < 7: raise ValueError("Password must be at least 7 characters") if not any(map(str.islower, password)): raise ValueError("Password must contain a lowercase letter") if not any(map(str.isupper, password)): raise ValueError("Password must contain an uppercase letter") if not any(map(str.isdigit, password)): raise ValueError("Password must contain a digit") if not (set(password) & set('!@#$%^&*()')): raise ValueError("Password must contain a special character") # Code that sets the password goes here while password := input('Enter New Password: '): try: set_password(password) break except ValueError as msg: print(msg)This computes a strength score.
def password_strength(password): strength = 0 if len(password) < 7 else 1 if any(map(str.islower, password)): strength += 1 if any(map(str.isupper, password)): strength += 1 if any(map(str.isdigit, password)): strength += 1 if set(password) & set('!@#$%^&*()'): strength += 1 return strength while password := input('Enter New Password: '): print(password_strength(password))And if you love unreadable one-liners:
def valid_password(p): return all([len(p) > 0, any(map(str.islower, p)), any(map(str.isupper, p)), any(map(str.isdigit, p)), set(p) & set('!@#$%^&*()')]) while password := input('Enter New Password: '): print(valid_password(password))It is good to know about any() and all(). To use any() or all() affectively it is also good to know about map() and list comprehensions.