Python 3.4,我无法让这个密码验证程序工作

时间:2015-02-20 15:23:08

标签: python-3.x

我正在尝试使用此密码验证程序,但我仍然收到密码不符合或不符合要求的消息。我用来测试它的密码确实符合并匹配。

enter code here
UPPER = "ABCDEFGHIJKLMNOPQRSTUVWYXZ"
LOWER = "abcdefghijklmnopqrstuvwxyz"
NUMBER = "1234567890"

def main() :
    password1 = input("Enter your password: ")
    password2 = input("Re-enter your password: ")
    validPword = False

while validPword == False :
    validPword = isValidPassword(password1,password2)
    if validPword == True :
        print("That pair of passwords will work.")
    else :
        print("Passwords didn't match or didn't have the required   properties.")
        password1 = input("Enter your password: ")
        password2 = input("Re-enter your password: ")

def isValidPassword(password1,password2) :
    equal = pEqual(password1,password2)
    length = pLength(password1)
    upper = pUpper(password1)
    lower = pLower(password1)
    number = pNum(password1)
    if equal and length and upper and lower and lower == True:
        return True
    else:
        return False


def pEqual(password1, password2) :
    if password1 == password2 : return True
    else:
        return False

def pLength(password1) :
    if len(password1) >= 8 : return True
    else:
        return False

def pUpper(password1):
    for i in range(len(password1)) :
        if password1[i] in UPPER : return True
        else :
            return False

def pLower(password1):
    for i in range(len(password1)) :
        if password1[i] in LOWER : return True
        else :
            return False

def pNum(password1):
    for i in range(len(password1)) :
        if password1[i] in NUMBER : return True
        else :
            return False

main()

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

首先,您的代码无法正常工作,因为您正在尝试检查密码中的每个字符是大写还是小写。这显然是不可能的。

为了大大简化您的代码,您可以import re添加类似的内容,以确保您的密码只是字母和数字,长度为8或更长。

if re.match("^[A-Za-z0-9]{8,}$", password1)

然后简单地进行字符串比较以检查是否相等。做一些修改,你可以尝试类似以下的东西。代码可以缩短,但我避免了最有可能损害您理解的更改。如果您有任何理解,请告诉我。

import re

def main() :
    validPword = False
    equalityPword = False

    while (validPword and equalityPword) != True :
        password1 = input("Enter your password: ")
        password2 = input("Re-enter your password: ")        
        validPword = isValidPassword(password1,password2)
        equalityPword = pEqual(password1,password2)
        if validPword == True and equalityPword == True :
            print("That pair of passwords will work.")
            return
        elif validPword == False :
            print("Please only use valid characters and numbers, and ensure your password is long enough.")
        else :
            print("Passwords didn't match.")

def isValidPassword(password1,password2) :
    if re.match("^[A-Za-z0-9]{8,}$", password1) :
        return True
    else:
        return False


def pEqual(password1, password2) :
    if password1 == password2 : return True
    else:
        return False
main()