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
Break for loop in an if statement
提问by mansa
Currently having trouble with breaking this for
loop. I want to break it if the variable is not found in this list so it can move two another for
loop. It expects an indented block for the top of the for
loop, but if I change the position of the break
or of the start of the for
loop, 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, break
only 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: break
in that loop aswel
如果您也想跳出 while 循环,那么您可以添加if x in z: break
该循环 aswel