Day 011 of the 100 Days of Python challenge brings together the previous lessons in a command-line Blackjack game. The player competes against a computer dealer using random cards and standard score comparisons.
This is the most ambitious project in the series so far — it combines random card dealing, score calculation with a special rule for aces, a full player-versus-dealer turn structure, and running statistics across multiple rounds, all split across focused, well-named functions.
This guide walks through the complete Day 011 source code, explains how scoring and the dealer’s logic work, and explains two scoring fixes: hands with more than one ace, and hands that bust.
Project Overview
The program represents cards as numbers. Number cards keep their values, face cards are represented by 10, and an ace starts as 11. The deal_card() function chooses one card at random from a 13-value list representing a standard deck.
The calculate_score() function handles two important rules: a two-card total of 21 is Blackjack, represented internally by 0, and each ace changes from 11 to 1, one at a time, while a hand would otherwise exceed 21.
Source Code
The Day 011 project is contained in day011/main.py in the 100daysofpython repository:
# ======================
# Project Name: Day 11 - Blackjack Game
# Section: Beginner Python Projects
# Description: A simple command-line Blackjack game where the user plays against the computer (dealer). The game includes features such as card dealing,
# score calculation, and determining the winner based on standard Blackjack rules.
# ======================
# Import ASCII logo from external file
import random
from art import LOGO
# Display the blackjack logo and welcome message
print(LOGO)
print("*******************************************")
print("Welcome to The Blackjack Game!")
print("*******************************************")
# Returns a random card from the deck.
def deal_card():
cards = [2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11]
card = random.choice(cards)
return card
# Calculate the score of the given cards.
def calculate_score(cards):
if sum(cards) == 21 and len(cards) == 2:
# Blackjack
return 0
# Count aces as 1 instead of 11, one at a time, until the hand is 21 or under
while 11 in cards and sum(cards) > 21:
cards.remove(11)
cards.append(1)
return sum(cards)
# Compare scores and return (result_message, outcome) where outcome is "win", "lose", or "draw".
def compare(u_score, c_score):
# Busting always loses, even if the computer also busts
if u_score > 21:
return "You went over. You lose 😭", "lose"
elif u_score == c_score:
return "Draw 🙃", "draw"
elif c_score == 0:
return "Lose, opponent has Blackjack 😱", "lose"
elif u_score == 0:
return "Win with a Blackjack 😎", "win"
elif c_score > 21:
return "Opponent went over. You win 😁", "win"
elif u_score > c_score:
return "You win 😃", "win"
else:
return "You lose 😤", "lose"
# Initialize win/loss/draw counters
wins = 0
losses = 0
draws = 0
def play_game():
global wins, losses, draws
print(LOGO)
# Initialize user and computer hands, scores, and game over flag
user_cards = []
computer_cards = []
computer_score = -1
user_score = -1
is_game_over = False
# Deal two cards to both the user and the computer at the start of the game
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
# Main game loop
while not is_game_over:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f"Your cards: {user_cards}, current score: {user_score}")
print(f"Computer's first card: {computer_cards[0]}")
# Check for immediate game over conditions (Blackjack or user score over 21)
if user_score == 0 or computer_score == 0 or user_score > 21:
is_game_over = True
else:
user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
if user_should_deal == "y":
user_cards.append(deal_card())
else:
is_game_over = True
# Computer's turn: the computer will keep drawing cards until it reaches a score of 17 or higher, or if it gets a Blackjack (score of 0)
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
print(f"Your final hand: {user_cards}, final score: {user_score}")
print(f"Computer's final hand: {computer_cards}, final score: {computer_score}")
message, outcome = compare(user_score, computer_score)
print(message)
# Update the win/loss/draw counters based on the outcome of the game
if outcome == "win":
wins += 1
elif outcome == "lose":
losses += 1
else:
draws += 1
print(f"\nScore — Wins: {wins} | Losses: {losses} | Draws: {draws}")
# Ask the user if they want to play a game of Blackjack. If they type 'y', start a new game. If they type 'n', exit the program.
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
print("\n" * 20)
play_game()
How the Program Works
Representing Cards and Detecting Blackjack
if sum(cards) == 21 and len(cards) == 2:
return 0
Rather than adding a separate Boolean flag for “is this Blackjack,” the function returns 0 as a special sentinel value whenever the very first two cards add up to 21. Every function that checks a score — compare(), the game-over check — treats 0 as “this hand is a natural Blackjack,” which keeps the scoring logic in one place.
The Dealer’s Fixed Strategy
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
The dealer follows a simple, fixed rule common to real Blackjack: keep drawing cards until reaching at least 17, unless it already has a natural Blackjack. Unlike the player, the dealer never “chooses” to stop early — its strategy is entirely mechanical.
Splitting Behavior Into Small Functions
The game is broken into deal_card(), calculate_score(), compare(), and play_game(), each with one clear responsibility. This separation makes it possible to reason about (and test) the scoring logic independently from the turn-by-turn game flow — a habit worth carrying into any larger program.
Two Scoring Rules Worth a Closer Look
An earlier version of this project had two scoring bugs. Both were fixed in the current code, and both are good lessons in testing edge cases.
Hands With Two or More Aces
# Count aces as 1 instead of 11, one at a time, until the hand is 21 or under
while 11 in cards and sum(cards) > 21:
cards.remove(11)
cards.append(1)
return sum(cards)
The earlier version used if instead of while, so it converted at most one ace per call. Trace a hand of [11, 11, 10, 5], two aces, a 10, and a 5:
- The sum is 37, so the first ace becomes 1:
[11, 10, 5, 1], a sum of 27. - With
if, the function stopped there and reported 27, a bust. - With
while, the loop runs again: the second ace becomes 1, giving[10, 5, 1, 1], a sum of 17, which is the correct Blackjack value.
The loop stops as soon as the hand is 21 or under, or when there are no 11s left, so aces stay worth 11 whenever they can. A single ace with a 5 still scores 16, and two aces alone score 12.
Busting Always Loses
# Busting always loses, even if the computer also busts
if u_score > 21:
return "You went over. You lose 😭", "lose"
elif u_score == c_score:
return "Draw 🙃", "draw"
compare() checks the conditions in order and returns at the first match. The earlier version checked for a draw before checking whether the player had busted, so if both hands busted with the same total (say 23 and 23), the game called it a draw. In Blackjack the player who busts loses, whatever the dealer does, so the bust check now comes first. The order of if/elif conditions is part of the logic, not just style.
What This Project Teaches
Day 011 practices:
- Lists and random selection for simulating a deck of cards
- Encoding a special case (Blackjack) as a sentinel return value
- Using a
whileloop when a correction may need to happen more than once - Ordering
if/elifconditions so the most important rule wins - Breaking a larger program into small, focused functions
- Module-level state (
wins,losses,draws) shared across function calls withglobal
Running the Project
git clone https://github.com/victorhugo81/100daysofpython.git
cd 100daysofpython/day011
python main.py
The project requires the supporting art.py file in the same folder.
Possible Next Steps
Once you understand the code, try extending it:
- Skip the dealer’s drawing loop when the player has already busted, since the outcome is already decided
- Show the dealer’s hidden card being revealed before the dealer draws
- Add support for splitting a hand when the first two cards match
- Persist
wins,losses, anddrawsto a file so the running statistics survive between program runs
Conclusion
Day 011 of the 100 Days of Python challenge ties together everything from earlier days, random selection, functions, loops, and module-level state, into a genuinely playable Blackjack game. Its two scoring fixes are worth remembering: use a loop when a correction may be needed more than once, and put the rule that must always win at the top of an if/elif chain. Both bugs only showed up in rare hands, which is exactly why edge cases deserve deliberate testing.
View the Day 011 source code on GitHub, then continue through the repository’s project index as you build more Python programs, one day and one small project at a time.
Related Reading
Want to keep learning? These related guides pair well with this post:
