How to Pick a Random Card in Python
Last Updated :
21 Mar, 2023
The Python Random module is a built-in Python module, used to create random integers. Because these are pseudo-random numbers, they are not actually random. This module may be used to generate random numbers, print a random value from a list or string, and so on.
To choose a random card from a deck of cards in Python, you must first store all of the cards. Then select a card at random. However, there are 52 cards. it’s not a good idea to keep all of the cards in a list one by one. In Python, you must first save all of the cards in a data structure before selecting a random card. So, before we place a card in a data structure, let’s look at the various types of cards in a deck of cards.
To Pick a Random Card in Python follow the steps below:
Step 1: Import the random library
import random
Step 2: Store the signs and value of the cards
cards = ["Diamonds", "Spades", "Hearts", "Clubs"]
ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"]
Step 3: Using the random module, choose a random value from both the list and return the value
def pick_a_card():
card = random.choices(cards)
rank = random.choices(ranks)
return(f"The {rank} of {card}")
Step 4: Return and print the value
print(pick_a_card())
Example 1:
Python3
import random
cards = [ "Diamonds" , "Spades" , "Hearts" , "Clubs" ]
ranks = [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , "Jack" , "Queen" , "King" , "Ace" ]
def pick_a_card():
card = random.choices(cards)
rank = random.choices(ranks)
return (f "The {rank} of {card}" )
print (pick_a_card())
|
Output:
The [3] of ['Hearts']
Example 2:
In this method, instead of printing the suit names, we will print their symbols using Unicode.
Python3
import random
def pick_a_card():
suit = random.randint( 1 , 4 )
value = random.randint( 1 , 13 )
if suit = = 1 :
random_suit = '\u2660'
elif suit = = 2 :
random_suit = '\u2665'
elif suit = = 3 :
random_suit = '\u2666'
else :
random_suit = '\u2663'
if value = = 1 :
random_value = 'Ace'
elif value = = 11 :
random_value = 'Jack'
elif value = = 12 :
random_value = 'Queen'
elif value = = 13 :
random_value = 'King'
else :
random_value = value
return (f "The {random_value} of {random_suit}" )
print (pick_a_card())
|
Output:
The 4 of ♥
Example 3:
Python3
import random
cards = [ "♦️" , "♠️" , "♥️" , "♣️" ]
ranks = [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , "Jack" , "Queen" , "King" , "Ace" ]
def pick_a_card():
card = random.choices(cards)
rank = random.choices(ranks)
return (f "The {rank} of {card}" )
print (pick_a_card())
|
Output:
The ['Queen'] of ['♠️']
Share your thoughts in the comments
Please Login to comment...