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.
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
- Import the random and itertools in the program.
- Using the itertool module, create a list of tuples, where each tuple contains the card number and its suits.
- Use the random module to shuffle the list.
- 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
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], "of", deck[i])
Your Cards are: 4 of HEART 3 of HEART 5 of CLUB 7 of DIAMOND 12 of CLUB
Your Cards are: 10 of CLUB 6 of HEART 3 of CLUB 4 of CLUB 7 of SPADE
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:
- Top Online Python Courses and Certificates in 2021
- Best Python Books for Beginners and Advanced Programmers
- Python Interview Questions
- Best Python Projects for Python Developers
- What is Python Used For?
- Python vs Scala
- Python vs Node.js
- Best Python GUI Frameworks for Developers
- Python Frameworks
- 10 Best Python IDEs and Code Editors