仅使用基本编程退出功能

时间:2013-07-31 05:04:00

标签: python return

我正在完成我的任务,如果值返回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语句将(希望)重复执行其余代码直到游戏结束发生。这是非常基本的编程吗?任何输入都会很棒

2 个答案:

答案 0 :(得分:1)

在Python(以及大多数其他语言)中使用单个return语句是很好的,但您也可以使用其他语句。主要是关于使代码尽可能可读。

这是一个最后有一个最终回报的样本:

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)

答案 1 :(得分:0)

为什么不在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()