python - 中断外部循环 Python 函数其他选项

标签 python function break

我有一些代码:

def playAgain1():
    print("Would you like to keep boxing or quit while you are ahead? (y/n)")
    playAgain = input().lower()
    if(playAgain.startswith('y') == False):
        print("Whatever you chicken.")
        break

如果 playAgain() 不以 y 开头,我希望它打破循环。每当我尝试时,都会收到错误:

'break' outside loop

我怎样才能更好地编写它以使其发挥作用?

最佳答案

正如 Matt Bryant 的回答所述,您不能在循环之外中断,而只能从函数中返回。我想补充一点,您可能需要从函数返回一个值,以便主程序循环知道是返回开始还是退出:

def main():
    while True:
        # main game code goes here
        if not playAgain():
            break

def playAgain():
    print("Would you like to keep boxing or quit while you are ahead? (y/n)")
    response = input().lower()
    return response.startswith('y')

关于python - 中断外部循环 Python 函数其他选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198172/

相关文章:

jquery - 嵌套 jQuery.each() - 继续/中断

python - 设置 matplotlib 子图的绝对大小

Python 2.7 格式化数据以写入 csv

Javascript 函数破坏了整个程序?

c++ - 这是否完美地模仿了函数模板特化?

Ruby - 循环不会中断

python - 从 python 脚本中获取 Flattr 交易?

python - 如何在凸多边形的周长上生成随机/均匀点?

c++ - 如何将变量从 C++ 中的一个函数返回到 main,然后在另一个函数中使用它?

java - 如何从 while 循环内的 if 条件中断 while 循环?