在python中退出for循环

时间:2015-07-03 23:57:38

标签: python-3.x syntax

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

编辑:修复了12个或更多的char错误。显然,大写字母不算是字母,所以“'高'没有得到满足,因此没有产出。所以我在检查之前添加了c + = u,现在一切都很好。

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

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
    ...

由于某种原因,这不起作用。也许有一些我失踪的东西......如果有人可以帮我解决循环问题,那就太棒了!

提前致谢!

1 个答案:

答案 0 :(得分:0)

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

问题在于while g not in ['low', 'med', 'high'],如果if g == 'low': ... elif ... elif ... else: raise ValueError,问题确实会永远存在。 这可以使用.htaccess修复。建设而不是。