English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use the random module to shuffle a deck of cards randomly.
To understand this example, you should understand the followingPython programmingTopic:
# Python program to shuffle cards # Import modules import itertools, random # Make a deck of cards deck = list(itertools.product(range(1,14), ['Clubs', 'Hearts', 'Diamonds', 'Spades']) # 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 result
You got: 6 Diamonds 10 Clubs 2 Hearts 5 Hearts 13 Hearts
Note:Run the program again to deal cards randomly.
In the program, we use the product() function from the itertools module to create a deck of cards. This function performs the Cartesian product of two sequences.
These two sequences are1to13with numbers and four suits. Therefore, we have a total of13 * 4 = 52items in the deck, each card is a tuple. For example,
deck[0] = (1, 'Spade')
Our cards are ordered, so we use the shuffle() function from the random module to shuffle the cards.
Finally, we draw the first five cards and display them to the user. Each time the program is run, we get different outputs, as shown in the two outputs.
Here we use the standard modules itertools and random that come with Python.