使用功能突破while循环 [英] Break out of a while loop using a function
本文介绍了使用功能突破while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有什么方法可以打破使用函数的无限循环吗?例如,
Is there any way to break out of infinite loops using functions? E.g.,
# 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 c $ c> example(),但您可以使其返回值(例如:布尔值)以停止无限循环
As far as I'm concerned you cannot call break from within example()
but you can make it to return a value(eg : A boolean) in order to stop the infinite loop
代码:
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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文