Blackjack Python: Beginner Tutorial

This post may contain affiliate links.

Sharing is caring!

In this article we will walk through how to create a blackjack game in Python from scratch! If you’re new to Python you can check our beginner tutorial!

How to play blackjack

Before we start coding, let’s go over the basic rules that our game will follow. We will code a very simple version of blackjack, here are the rules:

  1. In blackjack, each card has a value – face cards (kings, jacks) are worth 10 and aces are worth 11.
  2. The dealer will begin by dealing two cards to themselves and two cards to you. These are the starting hands.
  3. You add up the value of all the cards in your hand to get your score.
  4. Once the starting hand is drawn, you can choose two options: hit or stand.
    1. If you Hit the dealer will deal you another card. 
    2. If you Stand you will not recieve any more cards. 
  5. The goal is to get closer to 21 than the dealer without going over. If you go over 21, you bust and you immedietly lose.
  6. You can continue to hit until you either bust or choose to stand
  7. Once you decide to stand, the dealer draws a card for themselves and whoever’s score is closest to 21 without going over wins!

Now that we know the rules, let’s start thinking about the code!

Step 1: Initializing Data Structures

Before we begin coding the game, let’s go over the different data structures we will use. We will be using three data structures for this game: lists, dictionaries, and tuples.

Lists

If you want a review of how lists in Python work you can check it out here

For our game, we will use 2 lists to keep track of the different cards and suits. We will also use a list as our deck later.

# The type of suit
suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
 
# The type of card
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

Dictionaries

Dictionaries are a super useful datatype in Python. The unique thing about dictionaries is that they hold key value pairs. Here is an example of what a dictionary looks like in Python:

d =  {"key1" : "value1", "key2": "value2"}

In this example dictionary, we have 2 keys with 2 corresponding values: key1 corresponds to value1 and key2corresponds to value2. If we wanted to retrieve the value corresponding to a key in the dictionary, we can index into the dictionary like this:

result = d["key1"]
print(result)

Output:

value1

The important thing to remember here is that in dictionaries, we uses a key to access a value. For our game, we will use this dictionary to keep track of the values of each card:

# The values of each card
cards_values = {"A": 11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

The keys are the cards and the values are the scores of that card. For example, if we wanted to find the corresponding score for a queen, we can access it like so:

cards_values["Q"]

Output:

10

Tuples

Tuples in python are collections of values and are surrounded by parenthesis. A simple tuple in python looks like this:

(1,2,3)

We will be using a tuple to represent each card. For example, the ace of spades would look like this:

("A", "Spades")

We can also index into tuples just like we index into lists:

card = ("A", "Spades")
print(card[0])
print(card[1])

Output:

A
Spades

Step 2: Import the Random Library

Python has many built-in functions. For example len() is the built-in function that returns the length of the list. If you want to use other functions outside of what’s already in Python, you can import a library. A library contains functions that you can use once you import it! 

For this game, we want to use the random library. The random library provides us with the random.shuffle() function. This function takes in a list and randomly shuffles it. We will use this function to shuffle our deck.

This will be our first line of code for the game:

import random

Step 3: Generating the Deck

Before we jump into coding the main part of the game, there are a couple of things we want to do to make it a little easier. First, we need to write a few helper functions. Each helper function will do one small part of the game for us. We will use them in the final larger playGame() function. 

We will use the cards and suits lists that we defined before. Let’s define these lists in our program.

# The type of suit
suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
 
# The type of card
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

Now let’s use another type of data structure we leaned above to assign values to the cards. Here we will use a dictionary to assign values to our card.

# The values of each card
cards_values = {"A": 11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

Now let’s write the function generateDeck(), which will deal with creating a deck that we can use to play a round of the game. In order to do this, we will use two for loops. Let’s start by looping through all of the values in the suits list:

def generateDeck():
    deck = []
    for suit in suits:

For each suit, we want to generate all of the cards Ace through King, and then add that card to our deck. In order to do that we can put another for loop inside the first one:

def generateDeck():
    deck = []
    for suit in suits:
        for card in cards:
            deck.append((card, suit))
    return deck

Once we loop through both for loops, we have generated our entire deck! Let’s take a look at what the deck looks like now:

generateDeck()
[('A', 'Spades'),
 ('2', 'Spades'),
 ('3', 'Spades'),
 ('4', 'Spades'),
 ('5', 'Spades'),
 ('6', 'Spades'),
 ('7', 'Spades'),
 ('8', 'Spades'),
 ('9', 'Spades'),
 ('10', 'Spades'),
 ('J', 'Spades'),
 ('Q', 'Spades'),
 ('K', 'Spades'),
 ('A', 'Hearts'),
 ('2', 'Hearts'),
 ('3', 'Hearts'),
 ('4', 'Hearts'),
 ('5', 'Hearts'),
 ('6', 'Hearts'),
 ('7', 'Hearts'),
 ('8', 'Hearts'),
 ('9', 'Hearts'),
 ('10', 'Hearts'),
 ('J', 'Hearts'),
 ('Q', 'Hearts'),
 ('K', 'Hearts'),
 ('A', 'Clubs'),
 ('2', 'Clubs'),
 ('3', 'Clubs'),
 ('4', 'Clubs'),
 ('5', 'Clubs'),
 ('6', 'Clubs'),
 ('7', 'Clubs'),
 ('8', 'Clubs'),
 ('9', 'Clubs'),
 ('10', 'Clubs'),
 ('J', 'Clubs'),
 ('Q', 'Clubs'),
 ('K', 'Clubs'),
 ('A', 'Diamonds'),
 ('2', 'Diamonds'),
 ('3', 'Diamonds'),
 ('4', 'Diamonds'),
 ('5', 'Diamonds'),
 ('6', 'Diamonds'),
 ('7', 'Diamonds'),
 ('8', 'Diamonds'),
 ('9', 'Diamonds'),
 ('10', 'Diamonds'),
 ('J', 'Diamonds'),
 ('Q', 'Diamonds'),
 ('K', 'Diamonds')]

We can see that all of the cards in a deck have been added to a list. Now we just have one last thing to do: shuffle our deck. We will use the random.shuffle() function from the random library. Let’s add this to our original generateDeck function.

def generateDeck():
    deck = []
    for suit in suits:
        for card in cards:
            deck.append((card, suit))
    random.shuffle(deck)
    return deck

What will happen now when we call on the function?

generateDeck()
[('8', 'Spades'),
 ('7', 'Spades'),
 ('10', 'Diamonds'),
 ('Q', 'Hearts'),
 ('K', 'Diamonds'),
 ('6', 'Spades'),
 ('2', 'Hearts'),
 ('4', 'Clubs'),
 ('5', 'Diamonds'),
 ('J', 'Diamonds'),
 ('A', 'Diamonds'),
 ('5', 'Hearts'),
 ('6', 'Clubs'),
 ('A', 'Clubs'),
 ('9', 'Spades'),
 ('7', 'Diamonds'),
 ('5', 'Clubs'),
 ('6', 'Hearts'),
 ('4', 'Diamonds'),
 ('K', 'Spades'),
 ('3', 'Diamonds'),
 ('K', 'Clubs'),
 ('8', 'Diamonds'),
 ('4', 'Spades'),
 ('K', 'Hearts'),
 ('J', 'Hearts'),
 ('4', 'Hearts'),
 ('10', 'Clubs'),
 ('8', 'Clubs'),
 ('3', 'Clubs'),
 ('5', 'Spades'),
 ('Q', 'Diamonds'),
 ('3', 'Hearts'),
 ('A', 'Spades'),
 ('8', 'Hearts'),
 ('2', 'Spades'),
 ('A', 'Hearts'),
 ('3', 'Spades'),
 ('9', 'Hearts'),
 ('J', 'Spades'),
 ('10', 'Spades'),
 ('Q', 'Spades'),
 ('10', 'Hearts'),
 ('Q', 'Clubs'),
 ('6', 'Diamonds'),
 ('9', 'Diamonds'),
 ('J', 'Clubs'),
 ('7', 'Clubs'),
 ('7', 'Hearts'),
 ('2', 'Diamonds'),
 ('9', 'Clubs'),
 ('2', 'Clubs')]

 If we look at our deck now, we can see it’s shuffled. Now we have a deck we can play the game with!

Step 4 : Getting the Card’s Value

Getting the corresponding value for a card is an important action that we will do multiple times. Let’s write a function that will help us take in a card (Which is a tuple Ex:(“A”, “Spades”)) and return back that card’s value (11). Recall the cards_values dictionary from before. We will use it for this function.

cards_values = {"A": 11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

def getCardValue(card):

We only need the first element of the card to calculate it’s value. Let’s extract it by indexing into the tuple:

cards_values = {"A": 11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

def getCardValue(card):
    key = card[0]

This will be the key that we use to index into our cards_values dictionary. Now we can index into the dicitonary using this key to get the card’s value.

cards_values = {"A": 11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

def getCardValue(card):
    key = card[0]
    value = cards_values[key]
    return value

Now that we have a function that gives us the cards value, we will use it to help us later!

Step 4: Dealing with a Turn

Next, we will write a function that handles a single turn. This will consist of:

  1. Picking a single card from the top of the deck
  2. Printing the card that is drawn for the user to see 
  3. Calculating and updating the score for that player 
  4. Printing and returning the updated score

This function will take in 2 arguments: the current deck and the players current score.

  1. First, let’s pick the first card off the deck (which is a list) and store it in a variable. Since the deck is already shuffled, we can use the List.pop(i) method to pick the first card. List.pop(i) takes in an index i, removes it from the list, and returns the value.
def turn(deck, current_score):
    card = deck.pop(0)

2. Next, we print the card value to the player so they can see what card was drawn:

def turn(deck, hand):
    card = deck.pop(0)
    print(">> ", card)

3. Now we want to start calculating the players updated score. In order to do this, we want to get the value of the card we just drew. Remember that we wrote a function earlier that will take in a card and give us back it’s value!

def turn(deck, current_score):
    card = deck.pop(0)
    print(">> ", card)
    cardValue = getCardValue(cards)

The players new score is the score they previously had (current_score) plus the value of the card that was just drawn (cardValue):

def turn(deck, current_score):
    card = deck.pop(0)
    print(">> ", card)
    cardValue = getCardValue(cards)
    new_score = current_score + cardValue

4. Finally, we can print and return the new score:

def turn(deck, current_score):
    card = deck.pop(0)
    print(">> ", card)
    cardValue = getCardValue(cards)
    new_score = current_score + cardValue
    print("Score: ", new_score)
    return new_score

We have a function that plays one turn for us!

Putting it all together

Now that we have written all of the helper functions we will use, we can start writing the final playGame() function! 

First, we want to generate a deck to use for our game. Remember that we have a function that we wrote to help us do this: generateDeck() function

def playGame():
    
    # Setup
    deck = generateDeck()

Next we want to have two variables to keep track of the players and the dealers scores.

def playGame():
   
    # Setup
    deck = generateDeck()
    dealerScore = 0
    playerScore = 0

Now we want to draw two cards for both the player and the dealer. Our turn() function draws a single card and updates the score. We will call the turn function twice for each player. The turn function also prints the card that is drawn, so we will also include some print messages to tell the user who the card is being drawn for and what the total score is afterwards:

def playGame():  
    
    # Setup
    deck = generateDeck()
    dealerScore = 0
    playerScore = 0
    
    print("-------------------------Dealers Hand-------------------------")
    dealerScore = turn(deck, dealerScore);
    dealerScore = turn(deck, dealerScore);
    print("Dealers score:", dealerScore)
    
    print("-------------------------Players Hand-------------------------")
    playerScore = turn(deck, playerScore);
    playerScore = turn(deck, playerScore);
    print("Your score:", playerScore)

Finally, let’s start writing the interactive part of the game! The user should be able to hit until they either bust or stand. We can acomplish this by using a while loop. We will use a variable, keepPlaying, to keep track of if the game is still going on (True), or if the game has ended (False). If the game has ended, we want the loop to stop. This is what our while loop will look like:

def playGame():  
    
    # Setup
    deck = generateDeck()
    dealerScore = 0
    playerScore = 0
    
    print("-------------------------Dealers Hand-------------------------")
    dealerScore = turn(deck, dealerScore);
    dealerScore = turn(deck, dealerScore);
    print("Dealers score:", dealerScore)
    
    print("-------------------------Players Hand-------------------------")
    playerScore = turn(deck, playerScore);
    playerScore = turn(deck, playerScore);
    print("Your score:", playerScore)

    print("-------------------------Begin Game-------------------------")
    keepPlaying = True
    while keepPlaying: 

Next, we will use the input function to get input from the user, and save it in the variable userChoice:

def playGame():  
    
    # Setup
    deck = generateDeck()
    dealerScore = 0
    playerScore = 0
    
    print("-------------------------Dealers Hand-------------------------")
    dealerScore = turn(deck, dealerScore);
    dealerScore = turn(deck, dealerScore);
    print("Dealers score:", dealerScore)
    
    print("-------------------------Players Hand-------------------------")
    playerScore = turn(deck, playerScore);
    playerScore = turn(deck, playerScore);
    print("Your score:", playerScore)

    print("-------------------------Begin Game-------------------------")
    keepPlaying = True
    while keepPlaying:   
        userChoice = input("HIT or STAND: ")

At this point, what we do next depends on if the user chose HIT or STAND. First, let’s deal with the case that the user picks HIT:

        if (userChoice == "HIT"):

In this case, we want to give the user another card using our turn() function. We also want to print to the user what the current scores are:

    userChoice = input("HIT or STAND: ")
    if (userChoice == "HIT"):
        playerScore = turn(deck, playerScore)
        print("Your total:", playerScore)
        print("Dealer total:", dealerScore)

If the user goes over 21 after their turn, we want to game to end. We can do this with a simple check if playerScore > 21. If they bust, we want to print to the user that they lost and change keepPlaying to False so we exit out of the loop. If the user didn’t bust, we stay in the loop. 

This is what everything put together so far should look like:

def playGame():  
    
    # Setup
    deck = generateDeck()
    dealerScore = 0
    playerScore = 0
    
    print("-------------------------Dealers Hand-------------------------")
    dealerScore = turn(deck, dealerScore);
    dealerScore = turn(deck, dealerScore);
    print("Dealers score:", dealerScore)
    
    print("-------------------------Players Hand-------------------------")
    playerScore = turn(deck, playerScore);
    playerScore = turn(deck, playerScore);
    print("Your score:", playerScore)

    print("-------------------------Begin Game-------------------------")
    keepPlaying = True
    while keepPlaying:       
        userChoice = input("HIT or STAND: ")
        if (userChoice == "HIT"):
            playerScore = turn(deck, playerScore)
            print("Your total:", playerScore)
            print("Dealer total:", dealerScore)
            if playerScore > 21:
                print("-------------------------You bust, dealer wins!-------------------------")
                keepPlaying = False

Now lets deal with the case that the user chooses STAND.

        elif (userChoice == "STAND"):

In this case, we want the dealer to take a turn. Let’s print to the user so that they know the dealer is picking a card and use our turn() function. We will also print the dealer’s and the user’s current scores after the turn, just like we did before:

        elif (userChoice == "STAND"):
            print("-------------------------Dealers Hand-------------------------")
            dealerScore = turn(deck, dealerScore)
            print("Your total:", playerScore)
            print("Dealer total:", dealerScore)

There are 4 scenarios we can encounter after the dealer draws their last card:

  • The dealer busts and the user wins (if dealerScore > 21:)
  • The dealer and user tie (if dealerScore == playerScore:)
  • The dealer is closer to 21 than the user and wins (if dealerScore > playerScore:)
  • The user is closer to 21 and wins (else:)

Let’s write out all of these conditionals and print out the proper message for each scenario:

            if dealerScore > 21:
                print("-------------------------Dealer busts, you win!-------------------------")
            elif dealerScore == playerScore:
                print("-------------------------Tie!-------------------------")
            elif dealerScore > playerScore:
                print("-------------------------You lose, dealer wins!-------------------------")
            else:
                print("-------------------------Dealer loses, you win!-------------------------")

Once the user chooses STAND and the final card is drawn, the game should end. So we will update our keepPlayingvariable at the end. This is what everything looks like together:

    elif (userChoice == "STAND"):
            print("-------------------------Dealers Hand-------------------------")
            dealerScore = turn(deck, dealerScore)
            print("Your total:", playerScore)
            print("Dealer total:", dealerScore)
            if dealerScore > 21:
                print("-------------------------Dealer busts, you win!-------------------------")
            elif dealerScore == playerScore:
                print("-------------------------Tie!-------------------------")
            elif dealerScore > playerScore:
                print("-------------------------You lose, dealer wins!-------------------------")
            else:
                print("-------------------------Dealer loses, you win!-------------------------")
            keepPlaying = False

We are almost finished, but there is one last case we need to account for. Since we are taking in user input, there is a chance that the user will type something that isn’t just HIT or STAND. We can account for this in an else statement, and just print to the user that what they entered is invalid.

def playGame():  
    
    # Setup
    deck = generateDeck()
    dealerScore = 0
    playerScore = 0
    
    print("-------------------------Dealers Hand-------------------------")
    dealerScore = turn(deck, dealerScore);
    dealerScore = turn(deck, dealerScore);
    print("Dealers score:", dealerScore)
    
    print("-------------------------Players Hand-------------------------")
    playerScore = turn(deck, playerScore);
    playerScore = turn(deck, playerScore);
    print("Your score:", playerScore)

    print("-------------------------Begin Game-------------------------")
    keepPlaying = True
    while keepPlaying:      
        userChoice = input("HIT or STAND: ")
        if (userChoice == "HIT"):
            playerScore = turn(deck, playerScore)
            print("Your total:", playerScore)
            print("Dealer total:", dealerScore)
            if playerScore > 21:
                print("-------------------------You bust, dealer wins!-------------------------")
                keepPlaying = False
        elif (userChoice == "STAND"):
            print("-------------------------Dealers Hand-------------------------")
            dealerScore = turn(deck, dealerScore)
            print("Your total:", playerScore)
            print("Dealer total:", dealerScore)
            if dealerScore > 21:
                print("-------------------------Dealer busts, you win!-------------------------")
            elif dealerScore == playerScore:
                print("-------------------------Tie!-------------------------")
            elif dealerScore > playerScore:
                print("-------------------------You lose, dealer wins!-------------------------")
            else:
                print("-------------------------Dealer loses, you win!-------------------------")
            keepPlaying = False
        else:
            print("Please enter valid input: 'HIT' or 'STAND'")

            
playGame()

Since we are in a while loop, we will just keep looping and asking for input from the user until they provide a valid input.

And that’s it! Here is everything we wrote all together and an example of what a game should look like:

import random

# The type of suit
suits = ["Spades", "Hearts", "Clubs", "Diamonds"]
 
# The type of card
cards = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]

# The values of each card
cards_values = {"A": 11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "10":10, "J":10, "Q":10, "K":10}

def generateDeck():
    deck = []
    for suit in suits:
        for card in cards:
            deck.append((card, suit))
    random.shuffle(deck)
    return deck

def getCardValue(card):
    key = card[0]
    value = cards_values[key]
    return value

def turn(deck, current_score):
    card = deck.pop(0)
    print(">> ", card)
    cardValue = getCardValue(card)
    new_score = current_score + cardValue
    return new_score

def playGame():  
    
    # Setup
    deck = generateDeck()
    dealerScore = 0
    playerScore = 0
    
    print("-------------------------Dealers Hand-------------------------")
    dealerScore = turn(deck, dealerScore);
    dealerScore = turn(deck, dealerScore);
    print("Dealers score:", dealerScore)
    
    print("-------------------------Players Hand-------------------------")
    playerScore = turn(deck, playerScore);
    playerScore = turn(deck, playerScore);
    print("Your score:", playerScore)

    print("-------------------------Begin Game-------------------------")
    keepPlaying = True
    while keepPlaying:      
        userChoice = input("HIT or STAND: ")
        if (userChoice == "HIT"):
            playerScore = turn(deck, playerScore)
            print("Your total:", playerScore)
            print("Dealer total:", dealerScore)
            if playerScore > 21:
                print("-------------------------You bust, dealer wins!-------------------------")
                keepPlaying = False
        elif (userChoice == "STAND"):
            print("-------------------------Dealers Hand-------------------------")
            dealerScore = turn(deck, dealerScore)
            print("Your total:", playerScore)
            print("Dealer total:", dealerScore)
            if dealerScore > 21:
                print("-------------------------Dealer busts, you win!-------------------------")
            elif dealerScore == playerScore:
                print("-------------------------Tie!-------------------------")
            elif dealerScore > playerScore:
                print("-------------------------You lose, dealer wins!-------------------------")
            else:
                print("-------------------------Dealer loses, you win!-------------------------")
            keepPlaying = False
        else:
            print("Please enter valid input: 'HIT' or 'STAND'")

            
playGame()

Here’s an example of output from the game:

Congratulations on creating a blackjack game in Python!

Python Blackjack Digital Resource

Do you want all of the material covered in this tutorial in an easy to use in classroom lesson? Grab our Python Blackjack Tutorial!

  • Comprehensive Python tutorial for teachers to introduce their students to Python.
  • Includes a 5-page PDF worksheet with an answer guide and a 27-slide Google Slides presentation.
  • Covers how to program a Blackjack Game in Python.
  • PDF worksheet contains exercises that gradually develop students’ programming skills.
  • Google Slides presentation is engaging and visually appealing, with interactive examples and illustrations.
  • Suitable for both experienced and new programming instructors.
  • Provides a solid foundation in Python programming for students to build on.
  • An excellent resource to teach Python in a fun and effective way.

Want all our Python Tutorials?

  • The Python Ultimate Bundle is an all-in-one package that includes all the Python tutorials you need to teach your students programming and game development.
  • The bundle includes tutorials on Python Basics, Python Lists, creating a story in Python, Rock Paper Scissors game, Fortune Teller game, Create Your Own Adventure game, Blackjack game, and Dice game.
  • Each tutorial is engaging, fun, and easy to follow with clear instructions and real-world examples.
  • The bundle includes resources such as PDF worksheets, answer guides, and Google Slides presentations to help students learn at their own pace.
  • This bundle is perfect for teachers who want to provide their students with a comprehensive introduction to Python programming and game development.

Want More Python?

If you are interested in learning more, check out our advanced Python tutorials here:

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *