这是对 NightShade 答案的改进,但也是总体上的总体改进。这是你第一次编码,所以恭喜你。我正在修改您的代码中的一些内容,以提高可读性、组织性、效率以及可扩展性和可重用性。
如果你有什么想让我解释的,请询问。此外,我修改了您计算密码强度的方式,但它可以很容易地恢复为您的原始密码。编辑:正如其他用户所建议的那样,您不应该真正存储密码。锻炼没关系,但你应该养成保护密码的习惯。如果您打算稍后创建登录系统,请考虑对密码进行哈希处理,将其存储在安全位置,然后将哈希输入与存储的哈希进行比较。它增加了一些保护。
from datetime import datetime # importing the date module
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
# Auxilliary Functions
# Enclosing in functions so that they can be reused, separated and organized
def passCheck(input_password):
date = datetime.now()
# sets the current date and time
dateString = datetime.strftime(date, "%m/%d/%Y %H:%M:%S")
# formats the string to look like m/d/t h:m:s
if len(input_password) < MIN_PASSWORD_LENGTH:
# Using text formatting for cleanliness and readibility
return(f"{dateString} ==> Password is too short: '{input_password}' (length = {len(input_password)})\n")
elif len(input_password) > MAX_PASSWORD_LENGTH:
return(f"{dateString} ==> Password is too long: '{input_password}' (length = {len(input_password)})\n")
else:
return 0
def letter_analysis(input_password):
special = ['!','@','#','$','%','^','&','*','(',')']
letters_found = 0
digits_found = 0
specials_found = 0
test = 0
for ch in input_password:
#Checking for isdigit(), isalpha() etc but adding everytime it finds it. You can change this.
test = test + 1*ch.isdigit()
letters_found += 1 * ch.isalpha()
digits_found += 1 * ch.isdigit()
specials_found += 2 * (ch in special)
# I would suggest adding 2, for example, as special characters should be valued more
return((letters_found and digits_found and specials_found, letters_found+digits_found+specials_found))
#Returning a tuple where first index will be True if letters, digits and specials exist, and second index is the count.
#Note: The count isn't a True count, since I'm counting special characters twice
## Main function
def main():
input_password = input("Enter your password: ")
try:
with open("password_attempts.txt", "a") as passFile:
# Opening text file as append, so that it doesn't erase what's there
passFile.write(passCheck(input_password))
#Passing it the result of the check function.
print(passCheck(input_password))
except TypeError:
print("Password Accepted")
#In case the return is 0, there will be TypeError. This is the case where it's accepted.
strength = letter_analysis(input_password)
#strength now holds the tuple.
evaluation = strength[0] + strength[1]
# Just an example. This is where strength is calculated and directly related to the letter analysis.
if evaluation > 5:
# Here you can use your judgement. I said 5 again as an example.
print(f"Password is strong: '{input_password}' (length/evaluation = {len(input_password)}/{evaluation})")
else:
print(f"Password is weak: '{input_password}' (length/evaluation = {len(input_password)}/{evaluation})")
main()
main()