ClintI
ClintI

Reputation: 27

python function not returning populated array

I'm working with an online class and can't seem to diagnose this bug. In the code below, if the player initially responds no to the prompt in draw_one_more() the correct value is returned. If the player takes one or more cards and eventually indicates no prior to busting, the value None is returned. I added a print statement directly before the return, and print statement shows the correctly populated value, but the value received from the function is None.

UPDATES I got a bit carried away after working with some recursive examples. As many suggested the problem doesn't require recursion, and TBF is probably a bad use case. I added some more code as requested.

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)

Upvotes: 0

Views: 141

Answers (1)

user15266715
user15266715

Reputation:

if in the first call to draw_one_more() draw_another == 'y', your function will always return None.

in recursive functions the value returned is always the first return, if your function does not return then you will get None.

EX:

first call to draw_one_more():

. draw_another == 'y'

then your function will execute the else statement and return None as you have no return statement inside the else.

EX:

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

is the same as

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

when you call foo(x), if x < 10 your function will return x, otherwise, None

Upvotes: 1

Related Questions