Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Dodger Game using Pygame in Python
Next article icon

Blackjack console game using Python

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Blackjack is a popular two-player card game that is played with a deck of standard playing cards around the world in casinos. The main criteria for winning this game are chance and strategy. The challenge of this game is to get as close to 21 points as possible without exceeding them. That is why it is also known as Twenty-One.

In this article, we will learn how to create a simple console-based blackjack game using the if-else statements in Python.

Rules of Blackjack game

Let's first understand the game's rules before writing the blackjack console game code.

  1. In blackjack, each player and dealer receives two cards. 
  2. The player can then choose to "play" (request another card) or "stop" (keep on hold until a new request is made). The goal in this game is to keep the sum of all card points equal to 21 without exceeding it.
  3. Face cards (i.e. Jack, Queen, and King) are worth 10 points, and Aces can be worth 11 points. If a player has more than 21 points then the player automatically loses the game.

Blackjack Console Game using Python

Now that we have a basic understanding of the rules of the game, let's start building the game using Python. We will use the following steps to build the game:

  1. Set up the deck of cards
  2. Shuffle the deck
  3. Deal the initial cards
  4. Allow the player to hit or stand
  5. Deal the dealer's cards
  6. Determine the winner

Implementation of Blackjack Console Game

Here is a detailed step-by-step explanation of the implementation of the blackjack game:

Step 1:

Firstly we import the Python Random module in our code for shuffling.

import random

Step 2:

After successfully importing the random module, we set up the deck by creating two lists: card_categories and cards_list. The deck is then constructed as a list of tuples, each representing a card (i.e. the first element of the tuple is a card, and the second element is categories of cards).

card_categories = ['Hearts', 'Diamonds', 'Clubs', 'Spades']  cards_list = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']  deck = [(card, category) for category in card_categories for card in cards_list]

Step 3: 

In this step, we create a function called card_values() which takes cards as input and returns the corresponding point of the card. Cards numbered from 2 to 10 have the same points as their number. Face cards like Jack, Queen, and King have 10 points, and Aces have 11 points.

def card_value(card):      if card[0] in ['Jack', 'Queen', 'King']:          return 10      elif card[0] == 'Ace':          return 11      else:          return int(card[0])

Step 4:

After creating the function, we will use the random.shuffle() method to shuffle the cards and also after using random.shuffle() method we will need to deal the initial card so that Two hands of cards are distributed: one for the player and one for the dealer. Each hand starts with two cards.

random.shuffle(deck)  player_card = [deck.pop(), deck.pop()]  dealer_card = [deck.pop(), deck.pop()]

Step 5:

Next, with everything done, let's write code that allows a player to "play" (i.e., take another card) or "stop" (i.e., stop the game), this code runs until the player's score reaches 21 or the player chooses to stop.

while True:      player_score = sum(card_value(card) for card in player_card)      dealer_score = sum(card_value(card) for card in dealer_card)      print("Cards Player Has:", player_card)      print("Score Of The Player:", player_score)      print("\n")      choice = input('What do you want? ["play" to request another card, "stop" to stop]: ').lower()      if choice == "play":          new_card = deck.pop()          player_card.append(new_card)      elif choice == "stop":          break      else:          print("Invalid choice. Please try again.")          continue        if player_score > 21:          print("Cards Dealer Has:", dealer_card)          print("Score Of The Dealer:", dealer_score)          print("Cards Player Has:", player_card)          print("Score Of The Player:", player_score)          print("Dealer wins (Player Loss Because Player Score is exceeding 21)")          break

Step 6:

After a player has completed his turn, it is the dealer's turn to draw cards until he has at least 17 points.

while dealer_score < 17:      new_card = deck.pop()      dealer_card.append(new_card)      dealer_score += card_value(new_card)    print("Cards Dealer Has:", dealer_card)  print("Score Of The Dealer:", dealer_score)  print("\n")

Step 7:

This is the final step in which we have to determine the winner by comparing the player and dealer scores.

  • If the player has scored greater than 21 then the player loses the game and the dealer wins the game. 
  • If the dealer has a score greater than 21 then the dealer loses the game and the player wins the game. 
  • If the player has scored higher than the dealer then the player wins the game. 
  • If the dealer has scored higher than the player's score then the dealer wins the game. 
  • If both player and dealer have the same score then the game is considered a tie.
if dealer_score > 21:      print("Cards Dealer Has:", dealer_card)      print("Score Of The Dealer:", dealer_score)      print("Cards Player Has:", player_card)      print("Score Of The Player:", player_score)      print("Player wins (Dealer Loss Because Dealer Score is exceeding 21)")  elif player_score > dealer_score:      print("Cards Dealer Has:", dealer_card)      print("Score Of The Dealer:", dealer_score)      print("Cards Player Has:", player_card)      print("Score Of The Player:", player_score)      print("Player wins (Player Has High Score than Dealer)")  elif dealer_score > player_score:      print("Cards Dealer Has:", dealer_card)      print("Score Of The Dealer:", dealer_score)      print("Cards Player Has:", player_card)      print("Score Of The Player:", player_score)      print("Dealer wins (Dealer Has High Score than Player)")  else:      print("Cards Dealer Has:", dealer_card)      print("Score Of The Dealer:", dealer_score)      print("Cards Player Has:", player_card)      print("Score Of The Player:", player_score)      print("It's a tie.")

Complete Implementation of Code

Here is the complete implementation of the Blackjack Console Game:

Python3
import random  card_categories = ['Hearts', 'Diamonds', 'Clubs', 'Spades'] cards_list = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'] deck = [(card, category) for category in card_categories for card in cards_list]  def card_value(card):     if card[0] in ['Jack', 'Queen', 'King']:         return 10     elif card[0] == 'Ace':         return 11     else:         return int(card[0])  random.shuffle(deck) player_card = [deck.pop(), deck.pop()] dealer_card = [deck.pop(), deck.pop()]  while True:     player_score = sum(card_value(card) for card in player_card)     dealer_score = sum(card_value(card) for card in dealer_card)     print("Cards Player Has:", player_card)     print("Score Of The Player:", player_score)     print("\n")     choice = input('What do you want? ["play" to request another card, "stop" to stop]: ').lower()     if choice == "play":         new_card = deck.pop()         player_card.append(new_card)     elif choice == "stop":         break     else:         print("Invalid choice. Please try again.")         continue      if player_score > 21:         print("Cards Dealer Has:", dealer_card)         print("Score Of The Dealer:", dealer_score)         print("Cards Player Has:", player_card)         print("Score Of The Player:", player_score)         print("Dealer wins (Player Loss Because Player Score is exceeding 21)")         break  while dealer_score < 17:     new_card = deck.pop()     dealer_card.append(new_card)     dealer_score += card_value(new_card)  print("Cards Dealer Has:", dealer_card) print("Score Of The Dealer:", dealer_score) print("\n")  if dealer_score > 21:     print("Cards Dealer Has:", dealer_card)     print("Score Of The Dealer:", dealer_score)     print("Cards Player Has:", player_card)     print("Score Of The Player:", player_score)     print("Player wins (Dealer Loss Because Dealer Score is exceeding 21)") elif player_score > dealer_score:     print("Cards Dealer Has:", dealer_card)     print("Score Of The Dealer:", dealer_score)     print("Cards Player Has:", player_card)     print("Score Of The Player:", player_score)     print("Player wins (Player Has High Score than Dealer)") elif dealer_score > player_score:     print("Cards Dealer Has:", dealer_card)     print("Score Of The Dealer:", dealer_score)     print("Cards Player Has:", player_card)     print("Score Of The Player:", player_score)     print("Dealer wins (Dealer Has High Score than Player)") else:     print("Cards Dealer Has:", dealer_card)     print("Score Of The Dealer:", dealer_score)     print("Cards Player Has:", player_card)     print("Score Of The Player:", player_score)     print("It's a tie.") 

Output:

Output of the console-base Blackjack game in Python
Output of the console-base Blackjack game in Python

Next Article
Dodger Game using Pygame in Python
author
ishukatiyar16
Improve
Article Tags :
  • Python
  • Python numpy-Random sampling
Practice Tags :
  • python

Similar Reads

  • Create Breakout Game using Python
    In this article we will build a clone of a famous game, 'Breakout'. We will build this game using one of Python's in-built libraries, Turtle. RequirementsAn IDE like PyCharm.Basics of PythonBasic knowledge of Python-Turtle.Willingness to learn.Project StructureWe want to keep the programming simple.
    15+ min read
  • Automate Chrome Dino Game using Python
    The Chrome Dino game appears when your internet connection is down in Chrome. In this article, we'll build a Python bot that can play the game by automatically making the dinosaur jump to avoid cacti and duck to avoid birds. Before we start coding, we need to install a few Python libraries: pyautogu
    4 min read
  • Brick Breaker Game In Python using Pygame
    Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by th
    14 min read
  • Snake Game in Python - Using Pygame module
    Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginne
    15+ min read
  • Dodger Game using Pygame in Python
    A Dodger game is a type of game in which a player has access to control an object or any character to dodge (to avoid) upcoming obstacles and earn points according to the number of items dodged if the player is not able to dodge the object the game will be over and final score will be displayed in t
    5 min read
  • Create Settings Menu in Python - Pygame
    Python is a flexible programming language with a large selection of libraries and modules for a variety of applications. Pygame menu is one such toolkit that enables programmers to design graphical user interfaces for games and apps. In this tutorial, we'll look at how to use the pygame menu package
    9 min read
  • KBC game using Python
    In this article, we will make a KBC game with almost all the features in CLI(Command Line Interface) mode using Python. Features of the game:Random questions every timeFour lifelinesAudience Poll50:50Double dipFlip the questionMade with the help of Matplotlib and NumPy libraries of python.Bar graph
    15+ min read
  • Color game using Tkinter in Python
    TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to
    4 min read
  • Create pong game using Python - Turtle
    Pong is one of the most famous arcade games, simulating table tennis. Each player controls a paddle in the game by dragging it vertically across the screen's left or right side. Players use their paddles to strike back and forth on the ball. Turtle is an inbuilt graphic module in Python. It uses a p
    3 min read
  • Building Space Invaders Using PyGame - Python
    In this article, we're going to build a Space Bullet shooter game using PyGame in Python.  The used file can be downloaded from here. Approach: Import the required module.Initialize the pygame.Create three functions:isCollision(): Which tells us whether the collision has occurred or not?game_over():
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences