0

所以我是python的初学者,我一辈子都想不通为什么它不会检查并添加每个字母

def howstrong (password):
    points = len(password)
    charactersallowed = ["!", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+"]

    for ch in password:
        if ch.isupper():
            points= points+5
        elif ch.islower():
            points = points+5
        elif ch.isdigit():
            points = points+5
        elif ch in charactersallowed:
            points= points+5
        else:
            points = points+0
        return points

如果我输入密码密码!在我的代码中,它告诉我我的积分是 14,但对于这个密码,它应该是 24?下面我将添加我的其余代码,但我怀疑它在那部分,我相信我的 for 循环中的某个地方有错误。

def checkingmain():

    while 1:
        p = input("\nEnter password: ")
        if len(p) < 8 or len(p) > 24:
            print("Password must be 6 to 12 characters.")
        elif input("Re-enter password: ") != p:
            print("Passwords did not match. Please try again.")

        else:
            score= howstrong(p)
            if not score:
                print("Invalid character detected. Please try again.")

            else:
                if score <= 0:
                    print("your password is weak",score)
                elif score>0 and score<20:
                    print("your password is medium",score)
                else:
                    print("your password is strong",score)
            break

如果有人能为有点python的初学者提供一个可以理解的解决方案,我将不胜感激。

4

3 回答 3

5

它只检查第一个字符,因为您在循环内返回。将您的 return 语句移回一个缩进,因此它不在 for 循环内。

于 2017-10-07T20:31:57.827 回答
1

由于您在循环中有 return 语句,因此它只在从函数返回之前运行循环一次。如果您将退货声明移回一个选项卡,它应该可以工作

于 2018-03-31T23:05:49.810 回答
0

return 语句位于 for 循环内,因此当您的程序第一次到达 for 循环的末尾时,它只是从函数返回,因此您的 for 循环终止。如下所示对您的代码稍作改动将对您有所帮助。

for ch in password:
    if ch.isupper():
        points= points+5
    elif ch.islower():
        points = points+5
    elif ch.isdigit():
        points = points+5
    elif ch in charactersallowed:
        points= points+5
    else:
        points = points+0
return points

希望能帮助到你 !

于 2017-10-07T20:39:13.070 回答