Python Program to Shuffle Deck of Cards


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

A deck of cards is a set of 52 rectangular-shaped cards, each of which is printed with a unique combination of a suit (hearts, diamonds, clubs, or spades) and a value (ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, jack, queen, or king).

In a standard deck of cards, there are 13 cards in each suit, with the values ranging from ace (which can count as either 1 or 11) to king (which counts as 10). The cards are typically made of paper or plastic, and are often used for playing a variety of card games, such as poker, blackjack, and solitaire.

The suits of the cards are typically represented by different colors and symbols. Hearts and diamonds are usually red, while clubs and spades are typically black. Each suit also has its own symbol, with hearts represented by a stylized heart shape, diamonds by a diamond shape, clubs by a clover or club shape, and spades by a stylized spade shape.


Python Code :

The below Python program to shuffle a deck of cards using the random module:


import random

# Define suits, ranks, and deck
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
deck = []

# Create deck of cards
for suit in suits:
    for rank in ranks:
        deck.append(rank + " of " + suit)

# Shuffle deck
random.shuffle(deck)

# Print shuffled deck
print(deck)

Explanation:

  1. The random module is imported to allow for randomization of the deck.
  2. The suits and ranks of the deck are defined as lists.
  3. An empty deck list is created.
  4. The for loops iterate through the suits and ranks, creating each possible card and adding it to the deck.
  5. The random.shuffle() function shuffles the deck.
  6. The shuffled deck is printed.

An example shuffled Deck:


['6 of Spades', 'Ace of Diamonds', '10 of Diamonds', '2 of Spades', 'King of Clubs', '2 of Clubs', '9 of Hearts', '9 of Diamonds', 'Jack of Hearts', 'King of Spades', '6 of Diamonds', '4 of Spades', 'Jack of Diamonds', '7 of Diamonds', 'Ace of Spades', '4 of Clubs', 'Ace of Clubs', '4 of Hearts', '9 of Clubs', 'Jack of Spades', '10 of Hearts', '5 of Diamonds', '8 of Clubs', '7 of Spades', '5 of Clubs', '5 of Spades', '10 of Spades', 'Queen of Clubs', '9 of Spades', 'Queen of Spades', 'King of Diamonds', '6 of Hearts', 'Jack of Clubs', '5 of Hearts', '3 of Diamonds', '3 of Spades', 'Queen of Hearts', 'Ace of Hearts', '2 of Hearts', '8 of Hearts', '8 of Spades', '2 of Diamonds', 'Queen of Diamonds', '3 of Clubs', '8 of Diamonds', '10 of Clubs', '4 of Diamonds', '7 of Hearts', 'King of Hearts', '6 of Clubs', '7 of Clubs', '3 of Hearts']


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co