【问题标题】:Password Validation using Python使用 Python 进行密码验证
【发布时间】:2020-05-19 13:27:11
【问题描述】:

我正在尝试编写一个代码来验证您访问程序的密码。密码长度至少为 6 个字符,包含 1 个大写字母、1 个小写字母、1 个数字和 1 个标点符号。这就是我现在所拥有的:

def main():
    while True:
        password = input("Please enter the desired password: ")
        if not password.islower(): 
            print("This is NOT a valid password.")
        elif not password.isupper(): 
            print("This is NOT a valid password.")
        elif not password.isdigit():
            print("This is NOT a valid password.")
        elif not len(password) < 6:
            print("This is NOT a valid password.")
        else:
            print("This is a valid password.")
            break
main() 

由于某种原因,即使我写了一个有效的密码,它也会一直打印密码无效,有谁知道为什么会发生这种情况?此外,如何让代码检测到我写的密码中至少有 1 个标点符号?谢谢!

【问题讨论】:

  • 尝试用英语单词准确地解释您希望每个条件完成的内容。例如:if not password.islower(): 您希望哪些值符合此条件(因此无效)?您希望哪些值 匹配此条件(以便检查其他值)?现在,尝试验证这一点。例如,您可以为每个“不是有效密码”行使用不同的消息,以便查看满足哪个条件。
  • elif not len(password) &lt; 6:更改为elif len(password) &lt; 6:
  • @KarlKnechtel 使用if not password.islower(): 我希望它能检测我输入的密码是否小写,然后打印“Not a Valid Password”。
  • 仍然需要帮助还是已有有用的答案?

标签: python while-loop passwords


【解决方案1】:

你的代码做错了。也就是说,您正在检查整个密码是否较低,然后再次检查整个密码是否较高。由于这个原因,它总是显示not valid。但你需要检查的是,密码是否包含单个小写字符,是否包含单个大写字符,是否包含单个数字,长度至少应为 6。

为此,您必须使用any(),如果迭代中的任何项目为真,则返回 True,否则返回 False。

def main():
while True:
    password = input("Please enter the desired password: ")
    if not any(p.islower() for p in password): 
        print("This is NOT a valid password")
    elif not any(p.isupper() for p in password): 
        print("This is NOT a valid password")
    elif not any(p.isdigit() for p in password):
        print("This is NOT a valid password")
    elif len(password) < 6:
        print("This is NOT a valid password")
    else:
        print("This is a valid password")
        break
main() 

【讨论】:

    【解决方案2】:

    函数islower()isupper()isdigit()检查字符串的所有元素是否满足该条件。因此,例如,当您使用 islower() 时,您正在检查字符串中的所有字符是否都是小写。

    对于这种情况,我会使用正则表达式来检查每个条件。使用正则表达式,您可以自定义所有要检查的规则,而且学习起来并不难(参见文档here

    一个使用你所拥有的例子是

    import re
    
    password = input('Write a password: ')
    
    if re.search('[A-Z]+', password) is None:
        print('invalid password!')
    elif re.search('[a-z]+', password) is None:
        print('invalid password!')
    elif re.search('[0-9]+', password) is None:
        print('invalid password!')
    elif re.search('[' + string.punctuation + ']+', password) is None:
        print('invalid password!')
    elif len(password) < 6
        print('invalid password!')
    else:
        print('valid password!!')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-28
      • 2016-06-09
      • 2015-12-28
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多