如何在Python中检查3个条件框的同时使用函数和循环检查密码强度?

问题描述 投票:0回答:1

我有一个任务是创建一个密码检查,说明密码是强(勾选 3 个标准)、中等(勾选 2 个标准)还是弱(1 个或更少)。标准为: 1:包含 2 个或以上数字 2:长度为 6 个或更多字符 3:包含 1 个或更多特殊字符:~ !@ #$%^&*.

我尝试了很多并查找过,但不想导入任何内容,因为我的考试不允许这样做。我想使用 for 循环、if 语句和定义函数。并希望保持简单,我只是一个初学者。

password= str(input("What is the password? "))
specchar= ["!","~","@", "#", "$", "%", "^","&", "*"]
a=0
for item in specchar:
    a= a+1
def CountDigitsFor(password):
    res = []
    for i in password:
        if i.isdigit():
            res.append(i)
    return len(res)
def result(len(res), a)
    return len(res)+a
b=0
if len(password)>=6:
    b = b+1
if b == 1 and result == 3:
    print("Password is strong")
if b+result == 3 or b+result ==2 :
    print("Password is moderately strong")
if b+result <= 2:
    print("Password is weak")

除了用户输入之外,没有任何结果。 有人可以帮忙吗?

python if-statement count passwords definition
1个回答
0
投票

首先,使用比

a
b
更具描述性的变量名称。

添加一个计数器变量来计算满足条件的数量。

您可以使用内置的

sum()
函数来获取满足条件的字符数。

password= str(input("What is the password? "))
specchar= {"!","~","@", "#", "$", "%", "^","&", "*"}
count_specchar = sum(c in specchar for c in password)
count_digits = sum(c.isdigit() for c in password)

criteria_count = 0
if count_digits >= 2:
    criteria_count += 1
if len(password) >= 6:
    criteria_count += 1
if count_specchar >= 1:
    criteria_count += 1

if criteria_count == 3:
    print("password is strong")
elif criteria_count == 2:
    print("password is moderately strong")
else:
    print("password is weak")

© www.soinside.com 2019 - 2024. All rights reserved.