Python 使用函数中断while循环
有没有办法用函数打破无限循环?例如:Python 使用函数中断while循环,python,python-3.x,user-defined-functions,break,Python,Python 3.x,User Defined Functions,Break,有没有办法用函数打破无限循环?例如: # 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 wan
# 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
请解释为什么会发生这种情况,以及如何修复这种情况。就我而言,您不能从
示例()
中调用break,但您可以让它返回一个值(例如:布尔值),以停止无限循环
守则:
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
结束while-true循环的方法是使用
break
。此外,中断
必须在循环的直接范围内。否则,您可以利用异常将堆栈中的控制权交给处理它的任何代码
然而,通常值得考虑另一种方法。如果您的示例实际上接近您真正想要做的事情,即根据一些用户提示输入,我会这样做:
if raw_input('Continue? y/n') == 'y':
print 'You wish to continue then.'
else:
print 'Abort, as you wished.'
在循环内部中断函数的另一种方法是从函数内部调用
StopIteration
,并在循环外部调用exceptStopIteration
。这将导致循环立即停止。例如:
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
+1用于在需要复杂嵌套时使用异常。一个真实的例子是迭代器在完成时引发的
StopIteration
异常。