N.Mishimo
N.Mishimo

Reputation: 1

python transfer subroutine definitions to another subroutine

Is it possible to transfer definitions from one subroutine to another? I can't find a way to transfer dealthehand to playthegame without it saying "deckchoice is not defined"

def dealthehand():
  deck2=[123456789]
  deckchoice=random.choice(deck2)
  deckchoice2=random.choice(deck2)
  deckchoice3=random.choice(deck2)
  deckchoice4=random.choice(deck2)
  deckchoice5=random.choice(deck2)
  deckchoice6=random.choice(deck2)



def playthegame():

  dealthehand()
  print(deckchoice)

Upvotes: 0

Views: 50

Answers (1)

mhawke
mhawke

Reputation: 87124

The idea is to return a value from the function so that the calling code can access the result.

def dealthehand():
    deck2=[1, 2, 3, 4, 5, 6, 7, 8, 9]

    deckchoice=random.choice(deck2)
    deckchoice2=random.choice(deck2)
    deckchoice3=random.choice(deck2)
    deckchoice4=random.choice(deck2)
    deckchoice5=random.choice(deck2)
    deckchoice6=random.choice(deck2)

    return (deckchoice, deckchoice2, deckchoice3, deckchoice4, deckchoice5, deckchoice6) 

def playthegame():
    hand = dealthehand()
    print(hand)    # will print a tuple, e.g. (5, 8, 2, 2, 1, 3)

Access the individual cards in the hand by indexing the tuple, e.g. the 3rd card would be hand[2] (index starts at 0).


That's quite cumbersome to construct the return vale (a tuple in this case). You would be better off using a single complex variable to group the dealt cards together into a hand. You might use a tuple, list, dictionary, or your own custom class to do this - it depends on how you need to use it.

Here's an example using a list to represent a hand of 6 cards:

def dealthehand():
    cards = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    return [random.choice(cards) for i in range(6)]

This uses a list comprehension to create a list of 6 random cards.

Upvotes: 1

Related Questions