import random
suits = ["Diamonds", "Spades", "Hearts", "Clubs"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
def create_deck():
deck = set()
for suit in suits:
cards = {f"The {rank} of {suit}" for rank in ranks}
deck.update(cards)
return deck
def main():
deck = create_deck()
num_of_cards = int(input("How many cards would you like?: "))
print("\n Here are your cards:")
for _ in range(num_of_cards):
print("", deck.pop())
print(" There are", len(deck), "cards left in the deck.")
if __name__ == "__main__":
main()
I have tried putting the random.shuffle in some of the places that make sense to me but it just ends up throwing errors. The code works as it should with the exception of the cards dealt are always the same and I want them to be random every time.
>Solution :
You can either shuffle in create_deck before returning the deck, or in mainafter generating the deck.
I would tend to prefer shuffling in main as one could make the parallel to real life: getting a new (sorted) deck a cards, shuffling it, playing. From a practical point of view it doesn’t make a difference.
Note that you need to use a list as container as sets are unordered :
import random
suits = ["Diamonds", "Spades", "Hearts", "Clubs"]
ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]
def create_deck():
deck = [f"The {rank} of {suit}"
for suit in suits
for rank in ranks]
return deck
def main():
deck = create_deck()
random.shuffle(deck)
num_of_cards = int(input("How many cards would you like?: "))
print("\n Here are your cards:")
for _ in range(num_of_cards):
print("", deck.pop())
print(" There are", len(deck), "cards left in the deck.")
if __name__ == "__main__":
main()
Example:
How many cards would you like?: 5
Here are your cards:
The 9 of Clubs
The 3 of Hearts
The 10 of Hearts
The 4 of Spades
The Jack of Hearts
There are 47 cards left in the deck.
Alternative: shuffling in create_deck
def create_deck():
deck = [f"The {rank} of {suit}"
for suit in suits
for rank in ranks]
random.shuffle(deck)
return deck
You could also make it an optional parameter:
def create_deck(shuffle=False):
deck = [f"The {rank} of {suit}"
for suit in suits
for rank in ranks]
if shuffle:
random.shuffle(deck)
return deck
# in main
deck = create_deck(shuffle=True)