0

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.

1
  • 1
    Put user_hand.append(random.choice(cards)) instead of card = random.choice(cards). Then call draw(x) without to append part. However, this will draw cards with replacement, I am not sure if this is what you want to do. Commented Mar 18, 2021 at 10:54

4 Answers 4

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

May be this way

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

Comments

0

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))

Comments

0
  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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.