首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何停止函数

如何停止函数
EN

Stack Overflow用户
提问于 2015-01-06 23:53:47
回答 6查看 249.9K关注 0票数 42

例如:

代码语言:javascript
复制
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_winner中),并且函数end()执行,它将返回到computer()player(),因为没有任何行告诉计算机停止执行player()computer()。如何在Python中停止函数?

EN

回答 6

Stack Overflow用户

发布于 2015-01-06 23:56:51

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

这意味着你可以在你的函数中有很多地方返回它。如下所示:

代码语言:javascript
复制
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()
票数 60
EN

Stack Overflow用户

发布于 2015-01-06 23:57:53

在本例中,如果do_not_continueTrue,则不会执行do_something_else()行。相反,控制权将返回给任何调用some_function的函数。

代码语言:javascript
复制
def some_function():
    if do_not_continue:
        return  # implicitly, this is the same as saying `return None` 
    do_something_else()
票数 8
EN

Stack Overflow用户

发布于 2020-02-15 01:42:27

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

代码语言:javascript
复制
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 
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27802270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档