首页 > 解决方案 > 如何在 Python 中制作密码检查器?

问题描述

我正在尝试用 Python 制作一个简单的密码检查器。该程序要求用户输入超过 8 个字母/符号和 if/else 语句的密码,如果它不包含大写/小写字母和数字,但每次我输入内容时它都会打印“密码足够强”即使我没有输入大写/小写字母或数字。因此,如果有人可以帮助我,我将不胜感激。

这是代码:

password = input("Input your password: ")

if (len(password)<8):
  print("Password isn't strong enough")
elif not ("[a-z]"):
  print("Password isn't strong enough")
elif not ("[A-Z]"):
  print("Passsword isn't strong enough")
elif not ("[0-9]"):
  print("Password isn't strong enough")
else:
  print("Password is strong enough")

标签: pythonif-statementpasswords

解决方案


本次检查:

elif not ("[a-z]"):

什么都不做;它只是检查静态字符串的真值。由于"[a-z]"是一个非空字符串,它总是被认为是真的(或“真”),这意味着not "[a-z]"无论password. 您可能打算使用该re模块,您可以在此处阅读:https ://docs.python.org/3/library/re.html

这是一种无需正则表达式即可实现此检查的方法,使用 Python 的allany函数、其in​​关键字以及string包含方便字符串ascii_lowercase(如所有小写字母,对应于正则表达式字符类[a-z])的模块:

import string

password = input("Input your password: ")

if all([
    len(password) >= 8,
    any(c in password for c in string.ascii_lowercase),
    any(c in password for c in string.ascii_uppercase),
    any(c in password for c in string.digits),
]):
    print("Password is strong enough")
else:
    print("Password is not strong enough")

推荐阅读