Python 在 if 语句中中断 for 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41065354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 00:25:03  来源:igfitidea点击:

Break for loop in an if statement

pythonlistif-statementfor-loopbreak

提问by mansa

Currently having trouble with breaking this forloop. I want to break it if the variable is not found in this list so it can move two another forloop. It expects an indented block for the top of the forloop, but if I change the position of the breakor of the start of the forloop, it doesn't work. Help!

目前无法打破这个for循环。如果在此列表中找不到该变量,我想中断它,以便它可以再移动两个for循环。它期望for循环顶部有一个缩进的块,但是如果我更改循环break开始的位置或位置for,则它不起作用。帮助!

while cyclenumb <= 10000:

    for x in userpassword[k]:
        for z in lowercaselist:
            if x in z:
                newpasswordlist.append(z)
                k +=1
                break
        else:

    for x in userpassword[k]:
        for z in uppercaselist:
            if x in z:
                newpasswordlist.append(z)
                k +=1
                break
        else:

回答by Tom Fuller

You'll need to break out of each loop separately, as people have mentioned in the comments for your question, breakonly stops the loop which it's in

正如人们在您的问题的评论中提到的那样,您需要分别跳出每个循环,break只会停止它所在的循环

for x in userpassword[k]:
    for z in lowercaselist:
        if x in z:
            newpasswordlist.append(z)
            k +=1
            break

     if x in z: # added an extra condition to exit the main loop
        break

You'll need to do this for bothloops

您需要为两个循环执行此操作

If you want to break out of the while loop as well, then you can add if x in z: breakin that loop aswel

如果您也想跳出 while 循环,那么您可以添加if x in z: break该循环 aswel