Write a Python Program to Shuffle Deck of Cards

In this tutorial, we’ll be writing a Python program to shuffle a deck of cards.

A deck of cards consists of 52 cards, which are divided into four suits – hearts, diamonds, clubs, and spades – and thirteen ranks – Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King.

To shuffle a deck of cards in Python, we first need to create a deck of cards.

We can do this by creating a list of tuples, where each tuple represents a card and contains two elements – the rank and the suit of the card.

We can use a nested loop to create the deck of cards:

deck = [(rank, suit) for rank in range(1,14) for suit in ['hearts', 'diamonds', 'clubs', 'spades']]

This creates a list of 52 tuples, where each tuple represents a card in the deck.

Next, we can use the shuffle function from the random module to shuffle the deck of cards:

import random

random.shuffle(deck)

This will shuffle the deck list in place, meaning that the original list will be modified.

We can then print the shuffled deck of cards:

for card in deck:
    print(f"{card[0]} of {card[1]}")

This will print each card in the shuffled deck on a new line.

Putting it all together, our program to shuffle a deck of cards in Python looks like this:

import random

deck = [(rank, suit) for rank in range(1,14) for suit in ['hearts', 'diamonds', 'clubs', 'spades']]
random.shuffle(deck)

for card in deck:
    print(f"{card[0]} of {card[1]}")

And that’s it!

We now have a program that can shuffle a deck of cards in Python.