FelixF
FelixF

Reputation: 151

Python 3.x: function that deals cards to x amount of players and makes a list

So far I have this:

def make_deck():
    deck = []

for suit in "HDSC":
        for rank in "JQKA23456789T":
            deck.append(rank + suit)

    random.shuffle(deck)

    return deck

def cards(deck, number_players): # What should I do for this function?
    deck = make_deck()


    for i in range:
        hands = []
        player_hand = [deck.pop(), deck.pop()]

    return hands

I should be producing outputs that look like this:

hands = cards(deck, 3)
print(hands)
[['5H', '3H'], ['5S', '4S'], ['7H', '4H']]

So the user determines how many couple of cards are printed.

Upvotes: 0

Views: 688

Answers (2)

peachykeen
peachykeen

Reputation: 4411

I see a couple of errors as noted in the code below:

def make_deck():
    deck = []

    for suit in "HDSC":
        for rank in "JQKA23456789T":
            deck.append(rank + suit)

    random.shuffle(deck)
    return deck

def cards(deck, number_players):
    hands = []  # define hands outside of the for loop
    for i in range(number_players):  # You need to specify a range
        hands.append([deck.pop(), deck.pop()])  # give each player a hand size of 2
    return hands

# finally put it all together by creating a new deck and passing it into cards()
cards(make_deck(), number_players)

I tried my best to intuit what the program was meant to do. Is this what you were looking for?

Upvotes: 2

LUSAQX
LUSAQX

Reputation: 423

You can try this, and deck argument is redundant in your defined function cards(). But you can rewrite the code if you want deck is changeable.

import random

def make_deck():

   deck = []

   for suit in "HDSC":
    for rank in "JQKA23456789T":
        deck.append(rank + suit)

   random.shuffle(deck)

   return deck

def cards(number_players): 

   deck = make_deck()
   hands = []

   for i in range(number_players):

     hands.append([deck.pop(), deck.pop()])

   return hands

Recall function:

hands = cards(3)

print(hands)

Upvotes: 1

Related Questions