A Simple Python Program to Shuffle a Deck of Cards

Posted in

A Simple Python Program to Shuffle a Deck of Cards

Vinay Khatri
Last updated on June 10, 2022

    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:

    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:

    Leave a Comment on this Post

    0 Comments