2

有没有办法使用函数打破无限循环?例如,

# Python 3.3.2
yes = 'y', 'Y'
no = 'n', 'N'
def example():
    if egg.startswith(no):
        break
    elif egg.startswith(yes):
        # Nothing here, block may loop again
        print()

while True:
    egg = input("Do you want to continue? y/n")
    example()

这会导致以下错误:

SyntaxError: 'break' outside loop

请解释为什么会发生这种情况以及如何解决。

4

3 回答 3

3

就我而言,您不能从内部调用 breakexample()但您可以使其返回一个值(例如:布尔值)以停止无限循环

编码:

yes='y', 'Y'
no='n', 'N'

def example():
    if egg.startswith(no):
        return False # Returns False if egg is either n or N so the loop would break
    elif egg.startswith(yes):
        # Nothing here, block may loop again
        print()
        return True # Returns True if egg is either y or Y so the loop would continue

while True:
    egg = input("Do you want to continue? y/n")
    if not example(): # You can aslo use "if example() == False:" Though it is not recommended!
        break
于 2013-10-17T11:44:29.983 回答
1

结束 while-true 循环的方法是使用break. 此外,break必须在循环的直接范围内。否则,您可以利用异常将堆栈中的控制权交给处理它的任何代码。

然而,通常值得考虑另一种方法。如果您的示例实际上接近您真正想要做的,即取决于一些用户提示输入,我会这样做:

if raw_input('Continue? y/n') == 'y':
    print 'You wish to continue then.'
else:
    print 'Abort, as you wished.'
于 2013-10-17T12:09:03.607 回答
1

在循环内部跳出函数的另一种方法是从函数内部引发 StopIteration,并在循环外部除外 StopIteration。这将导致循环立即停止。例如,

yes = ('y', 'Y')
no = ('n', 'N')

def example():
    if egg.startswith(no):
        # Break out of loop.
        raise StopIteration()
    elif egg.startswith(yes):
        # Nothing here, block may loop again.
        print()

try:
    while True:
        egg = input("Do you want to continue? y/n")
        example()
except StopIteration:
    pass
于 2015-05-12T15:59:29.120 回答