密码检查器UpperCase

时间:2017-10-01 14:44:41

标签: python python-2.7

以下是我正在工作的小程序

  

构建密码检查程序。它将采用字符串输入。条件:   密码字符串必须包含至少一个大写字母,一个小写字母,   一个数字和长度必须至少8个字符。否则它会   说'密码无效'。

我正在尝试以下代码

Enter the password: niswdgER41
Password should contain atleast one uppercase character

但它不一致,即使它在那里也要求大写,

{{1}}

3 个答案:

答案 0 :(得分:1)

你有几个错误,但最重要的是你使用的所有方法检查整个字符串是否支持条件,而不是一次它的字符。

将其更改为:

def validate_password(pwd):
    conds = [
        lambda s: any(x.isupper() for x in s),
        lambda s: any(x.islower() for x in s),
        lambda s: any(x.isdigit() for x in s),
        lambda s: len(s) >= 8
    ]

    return all(cond(pwd) for cond in conds)

但是,如果您真的希望用户知道缺少的内容,可以使用以下实现:

def validate_password(pwd):
    conds = {
        "uppercase": lambda s: any(x.isupper() for x in s),
        "lowercase": lambda s: any(x.islower() for x in s),
        "number": lambda s: any(x.isdigit() for x in s),
        "length": lambda s: len(s) >= 8
    }

    valid = True
    for name, cond in conds.iteritems():
        if not cond(pwd):
            print "Password lacking " + name
            valid = False

    if valid:
        print "Password OK"
    else
        print "Password Invalid"
    return valid

答案 1 :(得分:0)

您可以使用列表解析检查字符串中的所有字符:

contains_upper_case_character = any([letter.isupper() for letter in password])

# contains_upper_case_character is True if password contains an uppercase letter.

如果你想将它扩展到一个大写字母:

password = 'StrinG12'
upper_case_letters = [letter.isupper() for letter in password].count(True)

print(upper_case_letters)
>>> 2

答案 2 :(得分:0)

def checkpassword ():
    password = input ("please enter password")




def menu ():
    print ("1. Check Password")
    print ("2. Generate Password")
    print ("3. Quit")
    optionchoice = input (" please chose a menu,1,2,3")
    if optionchoice == "1":
        checkpassword()
    elif optionchoice == "2":
        pass
    elif optionchoice == "3":
        pass
    else :
        print ("invalid answer!")
        menu()


menu()