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], "of", deck[i])
You got: 5 of Heart 1 of Heart 8 of Spade 12 of Spade 4 of Spade
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.
deck = (1, 'Spade').
Our deck is ordered, so we shuffle it using the function
now after the above steps, we draw the 1st five cards and display to the user.
Here we have used the standard modules
random that comes with Python.
- Program to Find LCM in Python
- Program to Find HCF or GCD in Python
- Program to find the area of Triangle in Python
- Program to Solve Quadratic Equation in Python
Ask your questions and clarify your/others doubts on Program to shuffle a deck of cards in Python by commenting. Python Documentation