Python Program to Shuffle Deck of Cards

542
views
Program to Shuffle Deck of Cards in Python
(Last Updated On: December 23, 2018)

In this program, you’ll learn how to Shuffle Deck of Cards in Python.

To properly understand this example to shuffle deck of cards in Python, you should have the knowledge of following Python programming topics:

  • Python for Loop
  • Python Operators
  • Python I/O and Import

Program to shuffle deck of cards

# import modules
import itertools, random

# make a deck of cards
deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club']))

# shuffle the cards
random.shuffle(deck)

# draw five cards
print("You got:")
for i in range(5):
   print(deck[i][0], "of", deck[i][1])

Output:

You got:
5 of Heart
1 of Heart
8 of Spade
12 of Spade
4 of Spade
shuffle deck of cards
Python Program to shuffle deck of cards

Note: To get different shuffle card, run this Program again.

In the above program, we used product() function in itertools module to create a deck of cards. This function performs the Cartesian product of the two sequence.

The two sequence are, numbers from 1 to 13 as we have 13 cards for each phase and the four suits. So, total we have 13 * 4 = 52 items in the deck of cards with each card as a tuple.

For e.g. deck[0] = (1, 'Spade').

Our deck is ordered, so we shuffle it using the function shuffle() in random module.

now after the above steps, we draw the 1st five cards and display to the user.

Here we have used the standard modules itertools and random that comes with Python.

Related Program:

Ask your questions and clarify your/others doubts on Program to shuffle a deck of cards in Python by commenting. Python Documentation