【问题标题】:How to make password checker in Python? [closed]如何在 Python 中制作密码检查器? [关闭]
【发布时间】:2021-07-08 22:58:18
【问题描述】:

我正在尝试用 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")

【问题讨论】:

  • 想想not ("[a-z]") 在做什么。首先,括号在这里没有用,所以它只是not "[a-z]"。所以not 运算符被应用于一个字符串。由于字符串非空,因此被认为是真的,所以not "[a-z]" 的计算结果为False。所以所有的elif 语句都等价于elif False:。请注意,它们根本不引用 password,因此 password 仅用于初始长度检查。
  • elif not ("[a-z]") 您似乎打算用这段代码来检查密码是否包含任何小写字母,但这不是这段代码实际上在做什么。
  • 如果你在 Linux 下运行,你可能想研究一下 PAM(Pluggable Authentication Modules),它是一个复杂的系统,但允许将这些东西抽象到配置文件中。它正在(慢慢地)被X/Open 采纳为标准。
  • 用你自己的话说,你觉得elif not ("[a-z]"):到底是什么规则?按照什么逻辑?

标签: python if-statement passwords


【解决方案1】:

这个检查:

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

什么都不做;它只是检查静态字符串的真值。因为"[a-z]" 是一个非空字符串,它总是被认为是真(或“真”),这意味着无论password 中有什么,not "[a-z]" 总是假的。您可能想要使用 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")

【讨论】:

    【解决方案2】:

    你可以用正则表达式简单地做到这一点,它会正常工作:

    import re
    password = input("Input your password: ")
    
    if (re.match(r"^.*[A-Z]", password) and re.match(r"^.*[0-9]", password) and len(password)>7 and re.match(r"^.*[a-z]", password) ):   
        print("Password is strong enough")
    else:
        print("Password is not strong enough")
    

    【讨论】:

      猜你喜欢
      • 2018-03-19
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2011-02-03
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      相关资源
      最近更新 更多