首页 > 解决方案 > 有没有更好的验证密码的方法?

问题描述

我正在检查我的密码是否符合此条件

  1. 长度至少为 10 个字符
  2. 至少包含 1 个大写字母
  3. 至少包含 1 个数字
  4. 至少包含字符 $、#、%、& 或 * 之一
  5. 不包含任何空格

我的代码:

password = input("enter a password ")
def passwordIsOk (password):
    symbols = "$#%&*"
    if len (password) > 10:
        if any(i.isupper() for i in password):
            if any(i.isdigit() for i in password):
                if " " not in password:
                    for i in range(0,5):
                        if symbols[i] in password:
                            passwordValid = True
                            if passwordValid == True:
                                print("ok buddy")
                            else:
                                print("Password must contain $#%&*")
                else:
                    print("Password must not contain spaces")
            else:
                print("Password must have at least 1 number")
        else:
            print("Password must have at least 1 capital letter")
    else:
        print("Password must be greater than 10 characters")
passwordIsOk(password)

它有效,但感觉不对:(

标签: python

解决方案


if您可以通过反转条件来避免这种嵌套结构。这使代码更具可读性,并将错误消息放在检查这些错误的条件旁边。

def passwordIsOk(password):
    symbols = "$#%&*"
    if len (password) <= 10:
        print("Password must be greater than 10 characters")
    elif not any(i.isupper() for i in password):
        print("Password must have at least 1 capital letter")
    elif not any(i.isdigit() for i in password):
        print("Password must have at least 1 number")
    elif " " in password:
        print("Password must not contain spaces")
    elif not any(s in password for s in symbols):
        print("Password must contain at least one of " + symbols)
    else:
        print("ok buddy")

password = input("enter a password ")
passwordIsOk(password)

推荐阅读