How to pick a random card in Python

In this Python tutorial, we will learn how to pick a random card from a deck of cards in Python. To learn how to select a random card in Python we gonna use random module.

In my previous tutorial, I have shown you How to print a deck of cards in Python

You can follow that tutorial if you wish.

Pick a random card in Python

In order to pick a random card from a deck of cards in Python, firstly you have to store all the cards. Then choose any random card. But there are 52 cards. I think it will not a good practice to store all the cards one by one in a list.

So, we are going to learn a smarter way to do this.

  1. At first, store all the values of the cards in a list ( values are from 2 to A )
  2. Then, store the signs of the card. (Club, Heart, Spade, Diamond )
  3. Using the random module, choose a random value from the first list
  4. Using the random module choose a random sign from the second list
  5. Just concatenate those random value and sign

Suppose we got value 8 from the first list as a random value and Club as a random sign from the second list.

Thus we can get a random card, which is 8 of CLUB

Python program to select a random card in Python from a deck of cards

import random
card_points =['A','K','Q','J','2','3','4','5','6','7','8','9','10']
card_signs =['Heart','CLUB','DIAMOND','SPADE']
random_point = random.choice(card_points)
random_sign = random.choice(card_signs)
random_card = random_point,random_sign
print(random_card)

Output:

$ python codespeedy.py
('5', 'SPADE')

That means the random card is 5 of SPADE

Each time you run the code, you will get a new random card.

Explanation of the program to choose a random card from a deck of cards in Python

At first, we have imported random module using the below line

import random

Learn more,

Using the below two lines, we have stored all the values and signs

card_points =['A','K','Q','J','2','3','4','5','6','7','8','9','10']
card_signs =['Heart','CLUB','DIAMOND','SPADE']

To choose a random card we used,

random_point = random.choice(card_points) 
random_sign = random.choice(card_signs)

these two variables are used to store the random value and sign of a random card.

Finally, we concatenate the value and sign by using the below line

random_card = random_point,random_sign

We know there is not only a single solution to a particular problem. if you find any other solution feel free to let others know using the below comment section.

 

Leave a Reply

Your email address will not be published. Required fields are marked *