python函数不返回填充数组

时间:2021-06-10 23:12:18

标签: python python-3.x recursion

我正在参加在线课程,但似乎无法诊断此错误。在下面的代码中,如果玩家最初对 draw_one_more() 中的提示没有响应,则返回正确的值。如果玩家拿了一张或多张牌并最终在破坏之前表示没有,则返回值 None 。我在返回之前直接添加了一个print语句,print语句显示了正确填充的值,但是从函数接收到的值是None。

更新 在处理了一些递归示例后,我有点不知所措。正如许多人所说,这个问题不需要递归,而 TBF 可能是一个糟糕的用例。我根据要求添加了更多代码。

def draw_card(hand, card_deck, todraw=1):
    for i in range(todraw):
        hand.append(card_deck[random.choice(card_deck)])
    return hand

player_hand = draw_card(hand=player_hand,
                        card_deck = card_deck,
                        todraw=2)

#3D - establish player draw loop
def draw_one_more(ahand):
    #print(player_hand)
    print(f"line 125 {ahand}")
    draw_another = input("Type 'y' to get another card, type 'n' to pass: ")
    print("Line 128 Draw another: " + draw_another)
    if draw_another != 'y':
        print(f"line 129 inside NO returning {ahand}")
        return ahand
    else:
        ahand = draw_card(hand=ahand,
                            card_deck = card_deck,
                            todraw=1)
        ascore = add_cards(ahand)
        #exit 2 - bust
        if ascore > 21:
            print(f"\tYour cards: {ahand}, current score: {ascore}: PLAYER BUSTS")
            print(f"\tComputer's first card: {computer_hand[0]}")
            return ahand
        #continue recursively
        print(f"\tYour cards: {ahand}, current score: {ascore}")
        print(f"\tComputer's first card: {computer_hand[0]}")
        draw_one_more(ahand)

#4 - computer run loop 
#first run player execution
player_hand = draw_one_more(player_hand)
print(f"line 148 player hand {player_hand}")
player_score = add_cards(player_hand)

1 个答案:

答案 0 :(得分:1)

如果在第一次调用 draw_one_more() draw_another == 'y' 时,您的函数将始终返回 None。

在递归函数中,返回的值总是第一个返回值,如果你的函数没有返回,那么你将得到 None。

例如:

第一次调用 draw_one_more():

。 draw_another == 'y'

然后您的函数将执行 else 语句并返回 None 因为您在 else 中没有 return 语句。

例如:

def foo(x):
    if (x < 10)
        return x
    else
        foo(x - 1)

相同
def foo(x):
    if (x < 10)
        return x
    else
        foo(x - 1)
        return None

当你调用 foo(x) 时,如果 x < 10 你的函数将返回 x,否则返回 None