How to pick 5 random cards from a 52‑card deck in Python

1 Answer

0 votes
import random

"""
A standard deck of 52 playing cards consists of four suits:
spades (♠), hearts (♥), diamonds (♦), and clubs (♣).

Each suit contains 13 ranks:
Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King.

Cards of spades and clubs are black, while hearts and diamonds are red.

Color is informational only — it does not affect shuffling or random selection.
"""

"""
    This program picks 5 random cards from a standard 52‑card deck.

    It uses:
    - Python lists to store ranks, suits, and the deck
    - random.shuffle for efficient randomization (Fisher–Yates internally)
    - Functions for clean structure

    Algorithm:
    1. Build the deck (52 strings).
    2. Shuffle using random.shuffle.
    3. Print the first 5 cards.
"""

def build_deck():
    """Build a full 52‑card deck."""
    ranks = ["2","3","4","5","6","7","8","9","10","J","Q","K","A"]
    suits = ["Clubs", "Diamonds", "Hearts", "Spades"]

    deck = []

    # Combine each rank with each suit → 52 unique cards
    for suit in suits:
        for rank in ranks:
            deck.append(f"{rank} of {suit}")

    return deck


def shuffle_deck(deck):
    """Shuffle the deck using Python's built‑in Fisher–Yates shuffle."""
    random.shuffle(deck)


def main():
    # Step 1: Build the deck
    deck = build_deck()

    # Step 2: Shuffle the deck
    shuffle_deck(deck)

    # Step 3: Draw the first 5 cards
    print("Your 5 random cards:")
    for i in range(5):
        print(deck[i])


if __name__ == "__main__":
    main()


"""
run:

Your 5 random cards:
2 of Clubs
4 of Hearts
6 of Diamonds
7 of Spades
5 of Spades

"""

 



answered 1 day ago by avibootz
...