In this post, we will write a python program to shuffle deck of card with example and algorithm so that you can understand each line of code more efficiently and accurately.

Many of us have played cards in our lives, whether for fun or while solving various mathematical problems related to a deck of cards during our school years.

so I thing almost all of us knows that deck of cards have 52 cards, with 13 hearts, 13 diamonds, 13 clubs, and 13 spades. Our task is to shuffle it using Python.

So let’s first understand how we can shuffle deck of cards with help of algorithm and then jump to writing a coding part for our better understanding.

Algorithm

1import random module (we use this module to randomly shuffle a deck of cards)
2import itertools module (we use this module to generate a list of cards using their product() function )
3take one variable called deck and generate a list of cards.
(list(itertools.product(range(1,14), ["heart", "spade", "club", "diamond"])))
4Using the shuffle() function from a random module, randomly shuffle a deck of cards.
(random.shuffle(deck))
5Print the first 5 randomly shuffled cards using for-loop.

After understanding algorithm now, we’re all set to start writing the code. But before we dive in, there are a few essential programming concepts you should be familiar with:

  1. random module
  2. itertools module &
  3. for-loop

Source Code

import random, itertools

# Generate all deck of cards (52 cards) 
deck = list(itertools.product(range(1,14), ["heart", "spade", "club", "diamond"]))

# shuffle deck of cards 
random.shuffle(deck)

# print first 5 randomly shuffled cards

for i in range(5):
    print(f"{deck[i][0]} of {deck[i][1]}")

Output-1

13 of club
11 of heart
6 of club
10 of heart
6 of heart

Output-2

3 of club
8 of club
4 of spade
7 of heart
12 of spade
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment