Search code examples
pythonplaying-cards

Blackjack program in python


I just started learning to program last week and I'm having trouble writing a blackjack program. I can generate a deck list but I can't seem to think of a way to assign the cards values according to the rules of blackjack. Like face cards are equal to 10, ace can be 1 or 1,1 and the rest are equal to their face value. I know my code is probably a mess to you guys, but I would rather continue with it and make mistakes and learn, rather than copy and pastes a pros work. So could you give me some tips to assign the cards values, thanks.

Here is what I have so far

import random
import time

deck = []
hand = []
dealer_hand = []
def deck_shuffle():
    for suit in ["Clubs", "Dimonds", "Hearts", "Spades"]:
        for face in ["Jack", "Queen", "King", "Ace"]:
            deck.append([face, suit])
        for num in range(2, 11):
            deck.append([num, suit])
    random.shuffle(deck)
    return deck



def deal_cards():
    for x in range(0,2):
        deal_card = deck.pop(0)
        hand.append(deal_card)
        deal_card = deck.pop(0)
        dealer_hand.append(deal_card)



deck_shuffle()
deal_cards()
print (deck)



print("Dealers hand is", dealer_hand)
print("Your hand is", hand)

Solution

  • You can use a dict here:

    Example:

    >>> card_vals = {"Jack" : 5, "Queen": 15, "King": 20, "Ace":10}
    >>> card_vals.update({ x:x for x in range(2,11)})
    >>> card_vals["Jack"]
    5
    >>> card_vals["Jack"]
    5
    >>> card_vals[2]
    2
    >>> card_vals[5]
    5