Python:如何停止一个函数?

use*_*671 21 python function

例如:

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
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果某个条件变为真(在函数check_winner中)并且函数end()执行它将返回到computer()或player(),因为没有行告诉计算机停止执行player()或计算机().你如何在Python中停止函数?

Hek*_*tor 24

一个简单的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();
Run Code Online (Sandbox Code Playgroud)


jez*_*jez 8

在本例中,do_something_else()如果do_not_continue是,则不会执行该行True。相反,控制将返回到调用 的任何函数some_function

def some_function():
    if do_not_continue:
        return  # implicitly, this is the same as saying `return None` 
    do_something_else()
Run Code Online (Sandbox Code Playgroud)


小智 7

这将结束该功能,您甚至可以自定义“错误”消息:

import sys

def end():
    if condition:
        # the player wants to play again:
        main()
    elif not condition:
        sys.exit("The player doesn't want to play again") #Right here 
Run Code Online (Sandbox Code Playgroud)