Python无导入实现密码强度检查(循环与函数)求助
密码强度检查代码修复方案
原代码的核心问题
- 特殊字符检查逻辑错误:原代码只是遍历特殊字符列表计数,根本没验证密码中是否包含特殊字符,导致
a的值固定为9,完全不符合需求。 - 函数定义语法错误:
result函数缺少冒号,且参数不能用len(res)这种表达式,必须是合法的参数名。 - 未调用函数:
CountDigitsFor和result函数都没有被调用,直接使用函数名进行数值判断,条件永远不成立,因此没有输出。 - 强度判断逻辑错误:强密码需要同时满足3项标准,原代码的条件判断逻辑混乱,无法正确匹配需求。
修正后的代码
password = str(input("What is the password? ")) specchar = ["!", "~", "@", "#", "$", "%", "^", "&", "*"] # 检查密码中是否包含至少1个特殊字符 has_special = False for char in specchar: if char in password: has_special = True break # 找到一个特殊字符即可停止检查 # 统计密码中的数字个数 def count_digits(password): digit_count = 0 for i in password: if i.isdigit(): digit_count += 1 return digit_count # 计算满足的标准项数 def calculate_score(has_special, digit_count, password_length): score = 0 # 标准1:包含2个及以上数字 if digit_count >= 2: score += 1 # 标准2:长度≥6字符 if password_length >= 6: score += 1 # 标准3:包含至少1个特殊字符 if has_special: score += 1 return score # 获取各项指标并计算分数 digit_count = count_digits(password) password_length = len(password) score = calculate_score(has_special, digit_count, password_length) # 判断并输出密码强度 if score == 3: print("Password is strong") elif score == 2: print("Password is moderately strong") else: print("Password is weak")
关键修改说明
- 特殊字符检查:改为遍历特殊字符列表,判断是否有字符存在于密码中,找到后立即终止循环提升效率。
- 数字统计函数:简化逻辑,直接计数而非用列表存储后取长度,更高效直观。
- 分数计算函数:明确对应3项标准,每满足一项加1分,逻辑清晰易读。
- 强度判断:根据分数直接匹配对应强度,避免原代码的逻辑混乱,确保每个输入都能输出正确结果。
内容的提问来源于stack exchange,提问作者sammiejansen
相关产品推荐
相关产品推荐

