给定以下代码(不起作用):
while True:
# Snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok.lower() == "y": break 2 # This doesn't work :(
if ok.lower() == "n": break
# Do more processing with menus and stuff
有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?
Break for外层和内部while循环:
while True:
while True:
print('Breaks inner "while" loop')
break # Here
print('Breaks outer "while" loop')
break # Here
或者,用if语句中断外部和内部while循环:
while True:
while True:
if True:
print('Breaks inner "while" loop')
break # Here
print('Breaks outer "while" loop')
break # Here
输出:
Breaks inner "while" loop
Breaks outer "while" loop
Break for outer和inner for循环:
for _ in iter(int, 1):
for _ in iter(int, 1):
print('Breaks inner "for" loop')
break # Here
print('Breaks outer "for" loop')
break # Here
或者,用if语句打破外部和内部for循环:
for _ in iter(int, 1):
for _ in iter(int, 1):
if True:
print('Breaks inner "for" loop')
break # Here
print('Breaks outer "for" loop')
break # Here
输出:
Breaks inner "for" loop
Breaks outer "for" loop
如果您只需要在复杂的for循环巢中测试边缘情况,则可以抛出1/0来引发异常。我保证不会告诉任何人。当您希望快速测试深度嵌套的for循环的单个迭代,并且不想跟踪大量break语句或注释掉大量代码时,这种方法非常方便。
是的,您可以将它包装在函数中并使用return,但在某些上下文中,这可能会非常麻烦。
入门级程序员的例子:
for i in first_iter:
for j in second_iter:
for k in third_iter:
print(i_want_to_run_this_once_and_stop_executing(i,j,k))
1/0
code_that_takes_a_long_time()
expensive_code()
在执行大量数据预处理的大型jupyter笔记本脚本中,这尤其方便。