打破外部循环Python函数的其他选项

时间:2013-08-12 23:16:01

标签: 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开头,我希望它能够打破循环。每当我尝试时,我都会收到错误:

  

'打破'外循环

我怎样才能更好地编写它以使其有效?

2 个答案:

答案 0 :(得分:2)

正如马特·布莱恩特的答案所说,你不能在一个循环之外突破,但可以从函数返回。我想补充一点,您可能需要从函数中返回一个值,以便主程序循环知道是返回开始还是退出:

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')

答案 1 :(得分:1)

break替换为returnbreak只能在循环中使用,而return可以在函数中的任何位置使用。最终代码如下所示:

def playAgain1():
    print("Would you like to keep boxing or quit while you are ahead? (y/n)")
    playAgain = input().lower()
    if not playAgain.startswith('y'):
        print("Whatever you chicken.")
        return
    else:
        # do whatever you do when they say yes