例如:
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()
it will go back to computer()
or player()
因为没有一行告诉计算机停止执行 player()
或 computer()
。如何停止 Python 中的函数?
原文由 user3711671 发布,翻译遵循 CC BY-SA 4.0 许可协议
一个简单的
return
语句将“停止”或返回函数;准确地说,它将函数执行“返回”到函数被调用的点——函数终止而无需进一步操作。这意味着您可以在整个函数中的许多地方返回它。像这样: