如何停止一个函数

新手上路,请多包涵

例如:

 def main():
    if something == True:
        player()
    elif something_else == True:
        computer()

def player():
    # do something here
    check_winner()  # check something
    computer()  # let the computer do something

def check_winner():
    check something
    if someone wins:
        end()

def computer():
    # do something here
    check_winner() # check something
    player() # go back to player function

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        # the player doesn't want to play again:
        # stop the program


    # whatever i do here won't matter because it will go back to player() or computer()

main()  # start the program

My problem is that if a certain condition becomes true (in the function check_winner ) and function end() it will go back to computer() or player() 因为没有一行告诉计算机停止执行 player()computer() 。如何停止 Python 中的函数?

原文由 user3711671 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 346
1 个回答

一个简单的 return 语句将“停止”或返回函数;准确地说,它将函数执行“返回”到函数被调用的点——函数终止而无需进一步操作。

这意味着您可以在整个函数中的许多地方返回它。像这样:

 def player():
    # do something here
    check_winner_variable = check_winner()  # check something
    if check_winner_variable == '1':
        return
    second_test_variable = second_test()
    if second_test_variable == '1':
        return

    # let the computer do something
    computer()

原文由 Hektor 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题