A Simple Python Program to Shuffle a Deck of Cards

By | October 3, 2021
Python Program to Shuffle Deck of Cards

Here in this article, we have provided a Python program that can shuffle a deck of cards. It is a simple Python program that generates 5 random cards.

Prerequisite Topics

In order to successfully implement and understand the Python program, you need to have a good understanding of the following concepts in Python:

  • Python for Loop
  • Modules in Python
  • Python Random Module
  • Python Built-in functions

Steps

  1. Import the random and itertools in the program.
  2. Using the itertool module, create a list of tuples, where each tuple contains the card number and its suits.
  3. Use the random module to shuffle the list.
  4. Print the first 5 tuples of the list. (You can increase or decrease the number as per to your liking.)

Python Program to Shuffle a Deck of Cards

Code:

import itertools, random
# it create a list of tuples
deck = list(itertools.product(range(1,14),['SPADE','HEART','DIAMOND','CLUB']))
random.shuffle(deck) #shuffel
print("Your Cards are:")
for i in range(5):
    print(deck[i][0], "of", deck[i][1])

Output 1:

Your Cards are:
4 of HEART
3 of HEART
5 of CLUB
7 of DIAMOND
12 of CLUB

Output 2:

Your Cards are:
10 of CLUB
6 of HEART
3 of CLUB
4 of CLUB
7 of SPADE

Conclusion

That sums up a simple Python code to shuffle a deck of cards. The Python program requires no user input and generates 5 cards randomly. That’s because the for loop here iterates 5 times. You can experiment with the code and make it generate more or fewer cards. For doing so, you need to increase or decrease the number of tuples printed.

People are also reading:

Vamware
Author: Vinay

I am a Full Stack Developer with a Bachelor's Degree in Computer Science, who also loves to write technical articles that can help fellow developers.

One thought on “A Simple Python Program to Shuffle a Deck of Cards

Leave a Reply

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