如何停止功能 [英] How to stop a function

查看:77
本文介绍了如何停止功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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中的函数?

My problem is that if a certain condition becomes true (in the function check_winner) and function end() executes it will go back to computer() or player() because there's no line that tells the computer to stop executing player() or computer(). How do you stop functions in Python?

推荐答案

一个简单的return语句将停止"或返回该函数;确切地说,它会将函数执行返回"到调用该函数的位置-该函数无需进一步操作即可终止.

A simple return statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.

这意味着在整个函数中可能会有许多地方可以返回. 像这样:

That means you could have a number of places throughout your function where it might return. Like this:

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

这篇关于如何停止功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆