在python中验证密码功能

时间:2017-11-20 21:00:27

标签: python python-3.x

如果密码小于3且大于20且密码不匹配,则验证密码功能将返回false。请有人指导我理解为什么我的逻辑失败并告诉我更好的方法吗?

def verifyPassword(password, password2):
    if(len(password) == len(password2):
        if(len(password) and len(password2) >= 3:
            if(len(password) and len(password2) < 20:
                if password == password:
                    return True
                else:                
                    return False
            else:
                return False
        else:
            return False
    else:
        False
print(verifyPassword("le3ather", "leather2"))
print(verifyPassword("leather", "leather2"))
print(verifyPassword("leather", "leather"))
print(verifyPassword("le", "Le"))
print(verifyPassword("leatherLeatherleather", "leatherLeatherleather"))

3 个答案:

答案 0 :(得分:0)

MINLEN = 3
MAXLEN = 20

def verifypassword(pw1, pw2):
    if pw1 != pw2:
        return False
    if len(pw1) < MINLEN:
        return False
    if len(pw1) > MAXLEN:
        return False

    return True


def test():
    tests = [
            ("le3ather", "leather2"),
            ("leather", "leather2"),
            ("leather", "leather"),
            ("le", "le"),
            ("thisiseverybittoolong", "thisiseverybittoolong"),
    ]
    for p1, p2 in tests:
        print(p1, p2, verifypassword(p1, p2))


if __name__ == '__main__':
    test()

答案 1 :(得分:-1)

if((len(password) == len(password2)) and (len(password) and len(password2)) >= 3 < 20 ):

应该是这个

if((len(password) == len(password2)) and (len(password) and len(password2)) >= 3 and (len(password) and len(password2)) < 20 ):

虽然我确信有一种更简单的方法,但这似乎是对代码的最小改动。

答案 2 :(得分:-1)

我不知道你的目标是什么,但这就是我为你所做的: https://gist.github.com/dgsbicak/96517f33e516ca4438c6e252149b8cbc

def verifyPassword(password, password2):
    count = 0
    # Rule 1
    pas = [password, password2]
    for p in pas:
        if len(p)<3:
            print("Password length is shorter than 3")
            break
        elif len(p)>19:
            print("Password length is longer than 19")
            break
        else: pass


    if password==password2:
        return "Password is correct"
    else:
        return "Password is not correct"

print(verifyPassword("le3ather", "leather2"))
print(verifyPassword("leather", "leather2"))
print(verifyPassword("leather", "leather"))
print(verifyPassword("le", "Le"))
print(verifyPassword("leatherLeatherleather", "leatherLeatherleather"))