I’m trying to make a blackjack game and I’m having issues with a recursive function returning none. I have a function to calculate the score of the hand and check if it’s over 21. If it is, it checks to see if there’s an 11 in the hand; if there is, another function gets called to change it to a 1 instead, then calls the function to calculate the score.
I’ve added a break point and it adds up just fine until it returns the total value back to the class variable
def get_score(self, hand):
total = 0
for card in hand:
total += card
if total > 21:
if 11 in hand:
return self.ace_conversion(hand)
else:
return total
def ace_conversion(self, hand):
index = hand.index(11)
hand[index] = 1
self.get_score(hand)
On another post, someone recommended making both sides of the if statement return and that’s when I started having this issue. Previously, it was:
…
if total > 21:
if 11 in hand:
self.ace_conversion(hand)
else:
return total
When I had this, it would calculate the correct value, then return the original value of the hand.
The cases are not exhaustive, you need to cover the scenario where the hand is greater than 21 without an 11 in hand.
Solution:
def get_score(hand):
total = sum(hand)
if total > 21 and 11 in hand:
index = hand.index(11)
hand[index] = 1
return get_score(hand)
else:
return total
Do note that though readable, this performs two linear scans on the hand.