I am having trouble using one function in another to deal cards. Here is what I have so far.
import random as rand
def create():
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
suites = ['H', 'C', 'D', 'S']
deck = [[r + s] for s in suites for r in ranks]
return deck
def cards_dealt (num_cards, num_players, deck):
rand.shuffle(deck)
print(cards_dealt(5, 3, deck))
I understand that the function is incomplete. I need num_cards to be the number of cards that each player receives, num_players to be the number of players, and deck to be the list of card strings from the function create(). For example, the print statement would reveal the 5 cards each of the three players gets from the list deck that has been shuffled. My problem is that whenever I write something, it says that deck is not defined.
Forget about your two functions, since they're both correct, and look at your top-level code:
Where does
deck
come from? Nowhere. Hence the exception.It's pretty obvious where you intended it to come from—you have a
create
function that ends with areturn deck
. You just aren't calling it anywhere.So you want:
… or, if you want to make it clearer that the global variable is unrelated to the two locals:
… or, if you want to make things more concise:
Beyond this problem,
cards_dealt
doesn't have areturn
, so it just returnsNone
. When your function is complete, there might be something worth printing out, but for now, while you're debugging what you have so far, it's not very useful.Meanwhile, if you want to print the shuffled deck, which could be useful, you'd do something like this:
When you later finish the function so it returns, say, a tuple of 3 lists of 5 cards, you'll probably want to store those return values for later as well as printing them, so it might go something like this:
There are certainly other ways to do it, but you could complete your function as so, in order to return a dictionary of your players and their hands:
Then, create your deck (that is where your "deck is not defined" problem comes in) and call your function:
Which returns:
The equivalent
cards_dealt
function, but with loops instead of the dict and list comprehensions is:Let me suggest an object-oriented approach where we will define the classes
Card
,Deck
andPlayer
.Using objects instead of lists of cards will provide a neat API to implement games. As you implement game logic, it will also make it easier to keep a single source of truth as to where each card is and which player has each card.
Deck API
Dealing cards
Output
Playing a card
The
card.where
attribute can be updated to indicate the position of a card. Since it is the single source of truth for card position, this updates theplayer.hand
property.Output
More features
The above API provides the basics to deal cards and move cards from hand to hand, but can be extended to implement new features.