Python:如何停止一个函数? [英] Python: How to stop a function?

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

问题描述

例如:

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

def player():
#在这里做某事
check_winner()
computer()#让计算机做一些事

def check_winner():
如果有人赢了,请检查一下

end()


def computer():
#在这里做某事
check_winner()#查看某物
玩家()#回到玩家功能


def end():
如果条件:
#玩家想再次玩:
main()
elif不条件:
#玩家不想再玩:
#停止该程序


#无论我在这里做什么都不重要,因为它会返回到玩家()或()
$ b main()#启动程序
em是如果某个条件成立(在函数check_winner中)并且函数end()执行,它将返回到computer()或player(),因为没有线条告诉计算机停止执行player()或computer( )。如何在Python中停止函数?

解决方案

简单的return语句会停止或返回函数,精确地它将'函数执行'返回到函数被调用的地方 - 函数被终止而不需要进一步的操作。



这意味着你可以有许多地方在你的功能可能会返回。
像这样:

  def player():
在这里做点什么
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电脑做某事
computer();


For example:

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

解决方案

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

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

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