I am having a hard time using a while loop to add a card to the list and keep updating the sum.
Currently I am getting an operand type error saying that I cannot add a list to a list. Ideally
every time the player chooses a new card with ‘y’ then the list would update and the score would update as well.
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def blackjack():
should_continue = True
player_card1 = int(random.choice(cards))
comp_card = random.choice(cards)
if input("Do you want to play? Type 'y' or 'n'\n") == 'y':
while should_continue:
add_card = int(random.choice(cards))
player_cards = [player_card1]
player_cards.append(add_card)
comp_card = random.choice(cards)
player_score = sum(player_cards)
print(f"Your cards: {player_cards}, current score:{player_score}")
print(f"Computer's first card: {comp_card}")
if input(f"Type 'y' to get another card, type 'n' to pass:") == 'y':
player_card1 = player_cards
comp_card = comp_card
else:
should_continue = False
#calculate()
else:
should_continue = False
blackjack()
>Solution :
You were creating nested lists. The cards were added like so
[10, 10]
[[10, 10], 10]
So, you can’t [10, 10] + 10
I’ve fixed it and removed some dead code. Consider using something like PyCharm for debugging, syntax check and other benefits
import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def blackjack():
should_continue = True
player_cards = [random.choice(cards)]
if input("Do you want to play? Type 'y' or 'n'\n") == 'y':
while should_continue:
player_cards.append(random.choice(cards))
comp_card = random.choice(cards)
player_score = sum(player_cards)
print(f"Your cards: {player_cards}, current score:{player_score}")
print(f"Computer's first card: {comp_card}")
if not input(f"Type 'y' to get another card, type 'n' to pass:") == 'y':
should_continue = False
blackjack()