0

I am trying to create a blackjack game in python and I've come to a standstill. I need to use the sum function in order to check if the player has over 21 or not but when I use .append, it inserts the new value into the player's hand as such. You now have ['K', 8, [4]] Then when sum tries to add it all together, it can't grab the last value. I believe this is because it is in it's own set of brackets. (Which is a list in a list?) Any help would be greatly appreciated! Thank you!

import random
deck = [2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9,
        9, 9, 9, 0, 0, 0, 0, "J", "J", "J", "J", "Q", "Q", "Q", "Q", "K", "K", "K", "K", "A", "A", "A", "A"]
value = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8,
          "9": 9, "0": 10, "J": 10, "Q": 10, "K": 10, "A": 1, "A": 11}
random.shuffle(deck)

player = [deck.pop() for i in range(2)]
dealer = [deck.pop() for i in range(2)]

print("You have", (player))
print("The dealer has", dealer)

def hit():
    playing = True
    while playing:
        hit = input("Do you want to hit or stand ")

        if hit == "hit":
            player.append([deck.pop()for i in range(1)])
            print("You now have" , player)
            print("The dealer has", dealer)
            if sum(player) > 21:
                print("You bust! The dealer wins and steals all your hopes and dreams!")
                playing = False


        elif hit == "stand":
            print("It is now the dealer's turn")
            playing = False

        else:
            print("Please choose either ""Hit"" or ""stand")

hit()
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • 1
    Why `player.append([deck.pop()for i in range(1)])`? Why not just `player.append(deck.pop())`? A list comprehension over a range of length 1 will only run once, then wrap the single value in a list. – Carcigenicate Apr 25 '20 at 17:27
  • I'm not sure that dupe is appropriate, since the existence of the list seems to be a mistake in the first place. – Carcigenicate Apr 25 '20 at 17:29
  • @Carcigenicate maybe, but it can still teach OP the difference between `append` and `extend` so they don't make the same mistake again (in case it happened to be `range(2)` in their code) – DeepSpace Apr 25 '20 at 17:30
  • In the `value` dict you can't have 2 keys, `A`, one being 1 and one being 11. keys in a dict are unique. – Chris Charley Apr 25 '20 at 18:08

0 Answers0