gpt4 book ai didi

python - 使用函数跳出 while 循环

转载 作者:行者123 更新时间:2023-11-28 21:57:46 24 4
gpt4 key购买 nike

有什么方法可以使用函数来打破无限循环吗?例如,

# 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

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

最佳答案

就我而言,您不能从 example() 中调用 break,但您可以让它按顺序返回一个值(例如:一个 bool 值)停止无限循环

代码:

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

关于python - 使用函数跳出 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19425714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com