Python 如何停止函数

Python 如何停止函数,python,function,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_wi

例如:

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

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

一个简单的
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()

在本例中,如果
do\u not\u continue
True
,则不会执行行
do\u something\u else()
。控件将返回到调用某个函数的函数

def some_function():
    if do_not_continue:
        return  # implicitly, this is the same as saying `return None` 
    do_something_else()
上面是一个非常简单的例子。。。我用
score=100
来表示游戏结束,为
check\u winner
编写了一份声明


您需要使用类似的方法将
score
传递到
check\u winner
,使用
game\u over=check\u winner(score)
。然后,您可以在程序开始时创建一个分数,并将其传递给
计算机
玩家
,就像正在处理
游戏
一样。

def function():
  while True:
    #code here

    break

使用“中断”停止该功能。

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

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 

可能您正在寻找
yield
,它与
return
相同,但它停止函数的执行,而不是终止函数,

return
终止函数,这就是您想要的吗?是的(只要它可以在不重新启动程序的情况下再次使用)。我忘记在问题中添加1个函数(main),但是我仍然有一个问题,就像其他人说的那样,return返回到调用第二个函数的函数(带有return语句的函数),因此它永远不会停止,将return添加到几个地方没有任何作用,程序仍然会执行,我到底需要在哪里写return?我希望程序返回main()如果玩家想,如果他不想,我想完全停止程序。所以我只需要在函数check_winner?Yes中的end()之前添加'return winner'(或just return(None)?),指定return的任何点都将终止函数执行并返回调用代码。由于“if”以“return”结尾,因此不需要添加“else”。在if语句的内容后面加上“returnfalse”就足够了。(这必须超出if语句的范围)break停止循环而不是函数:
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