例如:
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中停止函数?
发布于 2015-01-06 23:56:51
一条简单的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()
发布于 2015-01-06 23:57:53
在本例中,如果do_not_continue
为True
,则不会执行do_something_else()
行。相反,控制权将返回给任何调用some_function
的函数。
def some_function():
if do_not_continue:
return # implicitly, this is the same as saying `return None`
do_something_else()
发布于 2020-02-15 01:42:27
这将结束函数,您甚至可以自定义“错误”消息:
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
https://stackoverflow.com/questions/27802270
复制相似问题