给定以下代码(不起作用):
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
有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?
我想提醒你,Python中的函数可以在代码中间创建,并且可以透明地访问周围的变量以进行读取,也可以通过非局部或全局声明进行写入。
所以你可以使用一个函数作为“易碎的控制结构”,定义一个你想要返回的地方:
def is_prime(number):
foo = bar = number
def return_here():
nonlocal foo, bar
init_bar = bar
while foo > 0:
bar = init_bar
while bar >= foo:
if foo*bar == number:
return
bar -= 1
foo -= 1
return_here()
if foo == 1:
print(number, 'is prime')
else:
print(number, '=', bar, '*', foo)
>>> is_prime(67)
67 is prime
>>> is_prime(117)
117 = 13 * 9
>>> is_prime(16)
16 = 4 * 4
首先,您还可以考虑将获取和验证输入的过程作为一个函数;在该函数中,如果值正确,则返回值,如果不正确,则继续在while循环中旋转。这本质上避免了您解决的问题,并且通常可以应用于更一般的情况(打破多个循环)。如果你一定要在代码中保留这个结构,并且真的不想处理记帐布尔值……
你也可以用下面的方式使用goto(在这里使用一个愚人节模块):
#import the stuff
from goto import goto, label
while True:
#snip: print out current state
while True:
ok = get_input("Is this ok? (y/n)")
if ok == "y" or ok == "Y": goto .breakall
if ok == "n" or ok == "N": break
#do more processing with menus and stuff
label .breakall
我知道,我知道,“你不应该使用goto”之类的,但它在这种奇怪的情况下很管用。
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