0

我正在处理我的任务,如果值返回 True,我需要退出一个函数。这是一个钓鱼游戏(到目前为止,你们都帮了大忙!)我正在尝试弄清楚如何退出一个函数。

def TargetPlayer(player_number, pHands,sDeck):
"""User inputs which player they are choosing as the target player, returns
target players number"""
    gameoverhands = GameOverHands(pHands)
    if gameoverhands == True:
        **missing code here**
        return gameoverhands
    else:
        ShowMessage("TURN: Player " + str(player_number) + ", it's your turn. ")
        if player_number == 0:
            ask = raw_input("Who do you want to ask? (1-3) ")
            while not ask.isdigit() or ask not in "123":
            etc ....
        return other_values

我想要问的是,如果执行 if 语句,您是否可以有不同的 return 语句仅返回该值?gameoverhands 基本上是说你手中没有牌并且游戏结束了,所以我需要以某种方式直接跳转到游戏中的最终函数,而 else 语句将(希望)重复执行其余代码直到游戏结束发生。这可以通过非常基本的编程实现吗?任何输入都会很棒

4

2 回答 2

1

return在 Python(以及大多数其他语言)中有一个语句很好,但您也可以有其他语句。主要是为了使代码尽可能地可读。

这是一个最终返回的示例:

def TargetPlayer(player_number, pHands,sDeck):
    """User inputs which player they are choosing as the target player, returns target players number"""
    result = GameOverHands(pHands)
    if gameoverhands == True:
        **missing code here**
        result = gameoverhands
    else:
        ShowMessage("TURN: Player " + str(player_number) + ", it's your turn. ")
        if player_number == 0:
            ask = raw_input("Who do you want to ask? (1-3) ")
            while not ask.isdigit() or ask not in "123":
            etc ....
            result = "Thisnthat"
    return result

这重新定义了一个“内部”函数:

def outerfunc(cond):
    def inner1():
        print('inner1')
    def inner2():
        print('inner2')
    if cond:
        chosenfunc = inner1
    else:
        chosenfunc = inner2
    chosenfunc()

outerfunc(True)
outerfunc(False)
于 2013-07-31T05:18:49.853 回答
0

为什么不直接调用最终函数 if gameoverhands == True(或者更确切地说if gameoverhands)?

def TargetPlayer(player_number, pHands,sDeck):
"""User inputs which player they are choosing as the target player, returns
target players number"""
    gameoverhands = GameOverHands(pHands)
    if gameoverhands == True:
        final_function()
    else:
        ShowMessage("TURN: Player " + str(player_number) + ", it's your turn. ")
        if player_number == 0:
            ask = raw_input("Who do you want to ask? (1-3) ")
            while not ask.isdigit() or ask not in "123":
            etc ....
        return other_values

在这种情况下final_function应该是这样的:

def final_function():
    print "Goodbye!"
    sys.exit()
于 2013-07-31T05:20:05.010 回答