Spookr
Spookr

Reputation: 39

Returning multiple values in a for loop?

so long story short:

import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
user_hand = []
computer_hand = []

def draw(x):
  for c in range(0, x):
    card = random.choice(cards)
  return card

user_hand.append(draw(1))
    
print(user_hand)

Trying to get a function together that will loop through the cards list and pick a random item, however many times as specified by X, however no matter the number plugged into

user_hand.append(draw(x))

it always returns only 1 card, quite stumped. Any ideas? Thought it was the return in the function as return ends a code block when it's called but i wasn't sure.

Upvotes: 0

Views: 1819

Answers (4)

Onkar Raut
Onkar Raut

Reputation: 1

  1. Problem lies in the value you are passing to draw() as range function iterates over the start and end point so passing one will return you only one value!
  2. You also need to add another list to append the random choices selected during range()

Upvotes: 0

Altareos
Altareos

Reputation: 882

If you want to pick cards without replacement, the random.sample function does what you want.

def draw(x):
  return random.sample(cards, x)

user_hand.extend(draw(3))

Upvotes: 0

Alexey
Alexey

Reputation: 416

May be this way

def draw(x):
  result=[] 
  for c in range(0, x):
     card = random.choice(cards)
     result.append(card) 
return result

Upvotes: 0

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9590

It is because card is getting overwritten in each iteration and you only return the last value.

You can create a list and return the list instead:

def draw(x):
  random_cards = []
  for c in range(0, x):
    card = random.choice(cards)
    random_cards.append(card)
  return random_cards

user_hand.extend(draw(1))  # further you'll need extend here else it will create a list of lists

Upvotes: 1

Related Questions