【发布时间】:2021-05-01 22:36:11
【问题描述】:
你好,
我最近开始学习 python,由于我对 JavaScript 有所了解,所以我对 python 有了一点领先优势,这是大多数初学者在学习 python 时所拥有的。自从我开始学习 python 以来,我一直在接受挑战,同时也在做自己的小项目。我现在面临的挑战是制作一个密码验证器。我的问题:
我花了 2 个多小时试图弄清楚如何计算字符串(密码)中特殊字符和数字的数量。 我还没有完善计数,但我现在的主要问题是获取打印结果的功能
好的,我这里有柜台:
def password_validator():
password = input("Please input your password >>> ")
for element in password:
num_list = ['1','2','3','4','5','6','7','8','9','0',]
for x in num_list:
num_count = 0
if element.count(x):
num_count = 1
if element.count(x):
num_count = 2
num_pass_strength = 1
if num_count == 2:
num_pass_strength = 1
else:
num_pass_strength = 0
elif num_count == 0:
num_pass_strength = 0
spec_chars = ['!', '@', '#', '$', '%', '&', '*',]
for c in spec_chars:
spec_count = 0
if element.count(c):
spec_count = 1
if element.count(c):
spec_count = 2
if spec_count == 2:
spec_pass_strength = 1
else:
spec_pass_strength = 0
elif spec_count == 0:
spec_pass_strength = 0
这基本上计算密码中的数字和特殊字符的数量。
这是我计算密码强度的方法:
add_strength = 0
if num_pass_strength == 1:
add_strength += 1
if spec_pass_strength == 1:
add_strength +=1
pass_strength = add_strength
这为 add_strength 变量增加了一个强度,pass_strength 也从 add_strength 变量中获取了它的数据。
这就是我认为我遇到的问题:
if pass_strength == 1:
is_weak_pass = True
elif pass_strength == 2:
is_medium_pass = True
elif pass_strength == 3:
is_strong_pass = True
if is_weak_pass == True:
print("Weak")
elif is_medium_pass == True:
print("Medium")
elif is_strong_pass == True:
print("Strong")
这应该检查强度的值并为所需的输出定义一个布尔变量。
我现在的主要问题是,当我运行脚本并输入密码时,
它给我留下了这样的结果
Output:
Please input your password >>> &^%&^%
Weak
Weak
Weak
Weak
Weak
Weak
谁能告诉我我做错了什么。这真的让我很烦,我什至很想为我的另一个项目找出类似的东西。谢谢
完整代码:
def password_validator():
password = input("Please input your password >>> ")
for element in password:
num_list = ['1','2','3','4','5','6','7','8','9','0',]
for x in num_list:
num_count = 0
if element.count(x):
num_count = 1
if element.count(x):
num_count = 2
num_pass_strength = 1
if num_count == 2:
num_pass_strength = 1
else:
num_pass_strength = 0
elif num_count == 0:
num_pass_strength = 0
spec_chars = ['!', '@', '#', '$', '%', '&', '*',]
for c in spec_chars:
spec_count = 0
if element.count(c):
spec_count = 1
if element.count(c):
spec_count = 2
if spec_count == 2:
spec_pass_strength = 1
else:
spec_pass_strength = 0
elif spec_count == 0:
spec_pass_strength = 0
add_strength = 0
if num_pass_strength == 1:
add_strength += 1
if spec_pass_strength == 1:
add_strength +=1
pass_strength = add_strength
if pass_strength == 1:
is_weak_pass = True
elif pass_strength == 2:
is_medium_pass = True
elif pass_strength == 3:
is_strong_pass = True
if is_weak_pass == True:
print("Weak")
elif is_medium_pass == True:
print("Medium")
elif is_strong_pass == True:
print("Strong")
password_validator()
【问题讨论】:
-
使用调试器查看何时将这些
is_变量设置为True。 -
代码中有很多冗余,清理它可能有助于暴露错误。
标签: python arrays loops validation iteration