问题描述
为什么在循环中断后执行额外的代码。我想停止代码并修改一些输入,但代码在中断后继续并给我一个错误。
if condition:
for i in range(n):
if another condition:
do_somthing
else:
flag = True
for i in range(n:
if condition:
do_something
else:
flag = True
while flag:
try:
print('Erorr')
break
except:
break
# if break,I don't want to execute the rest of the code
t = []
for i in range(0,n):
t.append(i)
解决方法
Break 不会停止代码,它会跳出循环。如果你想停止执行,你应该抛出一个异常。
如果您仍想运行一些其他内容,但又想跳过您评论的部分,则可以使用 else
语句。
while flag:
# do something here
else:
# this will only be executed if the while does not break
https://docs.python.org/3/reference/compound_stmts.html#the-for-statement
""" 在第一个套件中执行的 break 语句终止循环而不执行 else 子句的套件。在第一个套件中执行的 continue 语句跳过套件的其余部分并继续下一项,如果没有下一项,则使用 else 子句。 """
例如
import random
flag = True
cnt = 0
while flag:
# do something here
cnt += 1
val = random.randint(0,10)
if val > 8:
break
if val < 2:
raise Exception("Raised an exception")
if cnt > 5:
flag = False
else:
# this will only be executed if the while does not break
print("You ran the while loop more than 5 times")
,
break
语句终止包含它的循环(在本例中 - try/except
。)
程序的控制流向紧接在循环体之后的语句。
如果 break
语句在嵌套循环内(循环在另一个循环内),则 break
语句将终止最内层的循环。