在 python 中退出 for 循环

Getting out of a for loop in python

编辑:大部分问题已修复。更正后的代码如下。出于某种原因,如果用户的输入是 12 个或更多字符,CheckPwd 函数将继续 return none。这就是循环永远持续下去的原因,所以 elif 是一个很好的修复。

编辑:也修复了 12 个或更多字符的错误。显然大写字母没有被算作字母,所以不满足 'high' 的标准,因此输出 none。所以我在检查之前添加了 c+=u ,现在一切都很好。

我正在尝试制作一个密码强度检查程序,出于某种原因,如果用户的输入长度超过 11 个字符,for 循环(CheckPwd 函数中的第一个遍历所有字符的循环string) 将永远持续下去。这是我的代码:

def CheckPwd(string):
    c = 0
    u = 0
    x = len(string)
    alph = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
    for s in string:
        for y in alph:
            if s == y:
                c += 1
            if s == y.upper():
                u += 1
c += u
if 4<=x<=7:
    g = 'low'
    return g
if 8<=x<=11 and 3<=c:
    g = 'med'
    return g
elif 12<=x<=15 and 5<=c and 2<=u:
    g = 'high'
    return g

print ('Welcome to Secure Password Checker! Here we will make sure your 4-15 character password is secure enough.')
usrpwd = input('Please enter your password: ')
while usrpwd==usrpwd:
    x = len(usrpwd)
    if 4<=x<=15:
        g = CheckPwd(usrpwd)
        if g == 'low':
            usrpwd = input('Password strength is too low, please enter a stronger one: ')
        if g == 'med':
            choice = input('Your password is ok, but it could use a little work. Would you like to enter a new one?(y/n): ')
            if choice == 'y':
                usrpwd = input('Please enter the new password: ')
            else:
                print('Here is your secure password: ' + usrpwd)
                break
        elif g == 'high':
            print('Congratulations! Your password is secure! Here is your password: ' + usrpwd)
            break
    else:
        usrpwd = input('Please enter a password that is 4-15 characters long: ')

我尝试在循环问题中打断(sc 是我用来打断的计数器):

for s in string:
    sc += 1
    if sc == x:
        break
    ...

由于某种原因,这没有用。也许我遗漏了什么......如果有人能帮我解决循环问题,那就太好了!

提前致谢!

for 循环,根据定义,不能产生无限循环。

问题出在您的 while 中,如果 g not in ['low', 'med', 'high'] 确实会永远持续下去。 这可以使用 if g == 'low': ... elif ... elif ... else: raise ValueError 修复。改为施工。