密码验证程序

Password Validating Program

我需要编写一个程序来检查以确保用户输入的密码传递了以下参数:

除了 "Consists of only letters, digits, and one of the special characters given below"。

我的一切正常

我不知道写什么来检查这个。有任何想法吗?任何有关清理代码或更有效地编写代码的提示也将不胜感激。

password = input("Enter a password: ")

import re

def main():
upper = sum([int(x.isupper()) for x in password])

lower = sum([int(x.islower()) for x in password])

digit = sum([int(x.isdigit()) for x in password])

length = len(password)

special = re.search("[!@#$%&*()]", password)

if length >= 8 and length <=24:
    if upper >=2:
        if lower >=2:
            if digit >=1:
                if special:
                    print("Acceptable password.")
                else:
                    print("Unacceptable.")
main()

创建允许字符池并使用 set 的强大功能来检查不需要的字符。

import string
pool = string.ascii_letters + string.digits + '!@#$%&*()_'

这会给你 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*()_'

现在您可以检查 difference 密码和字符池之间的差异。让您的密码为 'ABCD§12'.

set(password).difference(pool)

此代码将为您提供 {'§'}

所以你只需要检查差异结果的长度。如果是 0 一切都很好。